from rest_framework import serializers
from decimal import Decimal
import logging, json, datetime, pymysql, requests, os
from random import randint, shuffle
from django.conf import settings
from django_redis import get_redis_connection
from django.db.models import Count, Sum, Max, Min, Avg

from users.models import CustomerUser, User, Level, CustomerUserVice, CustomerUserViceInviterRecord
from merchants.models import *
from goods.models import *
from activities.models import *
from orders.models import *
from vouchers.models import *
from cashbonus.models import *
from businesses.models import *
from equity_mall.utils.utils import random_str
from equity_mall.utils.sync_img_to_local import make_qrcode4, make_qrcode1
from postallive.models import *
from equity_mall.utils.utils import redis_scheme_token_wyh, check_sign_contract_result, get_sign_contract_url
from equity_mall.utils.qiniu_storage import pic_upload
from businesses.utils import cancel_group_order
from orders.utils import schengle
from equity_admin.utils import contract_add_stamp

logger = logging.getLogger('django')


class LevelModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ['id', 'prov_name', 'city_name', 'district_name', 'branch_name']


class CustomerUserListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CustomerUser
        fields = ['id', 'realname', 'mobile', 'level_name', 'create_time', 'point']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class CustomerUserRetrieveModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_offline_str = serializers.CharField(source='get_is_offline_display', read_only=True)
    openid = serializers.SerializerMethodField(read_only=True)
    company_user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUser
        fields = ['id', 'username', 'realname', 'mobile', 'level', 'create_time', 'is_offline_str', 'openid', 'avatar',
                  'obtain_point', 'use_point', 'order_num', 'company_user', 'ali_user_id', 'idcode']

    def get_company_user(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_openid(self, obj):
        try:
            return obj.old_openid
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class CustomerUserPointRecordModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    business_type_str = serializers.CharField(source='get_business_type_display', read_only=True)

    class Meta:
        model = PointRecord
        fields = ['id', 'create_time', 'operate_type_str', 'business_type_str', 'point', 'point_balance', 'order_id']


class OrderGoodsModelSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    goods_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ['id', 'count', 'point', 'merchant', 'default_image', 'goods_name', 'price', 'level_name', 'goods_id']

    def get_level_name(self, obj):
        try:
            if obj.launched_goods:
                return obj.launched_goods.level.name
            else:
                return ''
        except:
            return ''

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except:
            return ''

    def get_goods_name(self, obj):
        try:
            return obj.goods.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        try:
            merchant = obj.merchant
            data['id'] = merchant.id
            data['merchant_name'] = merchant.name
        except:
            pass
        return data


class ManagerUserListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    is_developer_str = serializers.CharField(source='get_is_developer_display', read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'nickname', 'mobile', 'level_name', 'create_time', 'is_active', 'is_active_str',
                  'account', 'role_name', 'distributed_point', 'level_id', 'role_id', 'is_developer', 'is_developer_str','is_agreement',
                  'sign_time']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''


class ManagerUserRetrieveModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    create_user_nickname = serializers.SerializerMethodField(read_only=True)
    contract = serializers.SerializerMethodField(read_only=True)
    is_developer_str = serializers.CharField(source='get_is_developer_display', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'nickname', 'mobile', 'level', 'create_time', 'is_active', 'is_active_str',
                  'account', 'role_name', 'distributed_point', 'distributed_point_num', 'level_id', 'role_id', 'avatar',
                  'create_user_nickname', 'is_developer', 'is_developer_str', 'is_agreement', 'signature', 'sign_time',
                  'contract']

    def get_contract(self, obj):
        try:
            if obj.is_agreement == 1:
                if not obj.contract:
                    contract_pdf = f'管理承诺书_{obj.mobile}_{"%06d" % randint(0, 999999)}.pdf'
                    pdf_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/{contract_pdf}')
                    contract_add_stamp(pdf_path, obj.mobile, obj.sign_time.strftime("%Y-%m-%d"), obj.signature.url)
                    with open(pdf_path, 'rb') as f:
                        result = f.read()
                    pic_upload(result, contract_pdf)
                    obj.contract = contract_pdf
                    obj.save()
                    os.remove(pdf_path)
                    return f'https://circle.sutpay.cn/{contract_pdf}'
                else:
                    return obj.contract.url
            else:
                return ''
        except:
            return ''

    def get_create_user_nickname(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''


class LevelListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account', 'account_nine', 'level')


class LevelRetrieveSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account', 'account_nine', 'level', 'address', 'longitude', 'latitude', 'telephone')


class MerchantListModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_mall_str = serializers.CharField(source='get_is_mall_display', read_only=True)
    applyment_state_str = serializers.CharField(source='get_applyment_state_display', read_only=True)
    verify_state_str = serializers.CharField(source='get_verify_state_display', read_only=True)
    is_enter_auth = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'level_name', 'subject_type_str', 'subject_type', 'name', 'wyfMerchantID', 'branch_num',
                  'order_num', 'settlement_amount', 'create_time', 'short_name', 'settlement_amount_by_day',
                  'is_mall', 'is_mall_str', 'applyment_state', 'applyment_state_str', 'verify_state', 'verify_state_str',
                  'is_enter_auth')

    def get_is_enter_auth(self, obj):
        if obj.is_mall == 0:
            if obj.channel_id != 3:
                return 0
            else:
                return 1
        else:
            return 0

    def get_level_name(self, obj):
        try:
            if obj.applyment_state in [1, 4]:
                mall_applyment = MerchantMallApplyment.objects.filter(merchant_id=obj.id, applyment_type=1).last()
                if mall_applyment:
                    if mall_applyment.applyment_state == 4:
                        result = check_sign_contract_result(obj.ruiyinxinMerchantID)
                        if result['data']['sign_status'] == 3:
                            obj.applyment_state = 1
                            obj.verify_state = 1
                            obj.save()
                            mall_applyment.applyment_state = 1
                            mall_applyment.audit_time = datetime.datetime.now()
                            mall_applyment.save()
                    elif mall_applyment.applyment_state == 1:
                        result = get_sign_contract_url(obj.ruiyinxinMerchantID)
                        if result['result_code'] != 'fail':
                            if result['data']['open_status'] == 2:
                                if not mall_applyment.sign_url:
                                    signUrl = result['data']['signUrl']
                                    sign_url = make_qrcode1(obj.ruiyinxinMerchantID, signUrl, key=None)
                                    mall_applyment.sign_url = sign_url
                                mall_applyment.applyment_state = 2
                                mall_applyment.save()
                                obj.applyment_state = 2
                                obj.save()
                            elif result['data']['open_status'] == 3:
                                mall_applyment.applyment_state = 3
                                mall_applyment.reject_reason = result['data']['open_result']
                                mall_applyment.save()
                                obj.applyment_state = 3
                                obj.save()
        except:
            pass
        try:
            return obj.level.name
        except:
            return ''


class MerchantImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantImage
        fields = ['id', 'image']


class MerchantChannelModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantChannel
        fields = ['id', 'smid', 'sub_mchid', 'channel_mchid', 'channel_id']


class MerchantRetrieveModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    business_category_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    close_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    merchantimage_set = MerchantImageSerializer(many=True)
    channel_name = serializers.SerializerMethodField(read_only=True)
    merchantchannel_set = MerchantChannelModelSerializer(many=True)
    mall_applyment = serializers.SerializerMethodField(read_only=True)
    is_enter_auth = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'level', 'subject_type_str', 'subject_type', 'name', 'wyfMerchantID', 'branch_num',
                  'order_num', 'settlement_amount', 'store_address', 'managerName', 'managermobile', 'account_name',
                  'account_bank', 'account_number', 'identification_number', 'create_time', 'store_header_copy',
                  'short_name', 'open_work_time', 'close_work_time', 'merchantimage_set', 'store_logo_copy', 'business_category_id',
                  'business_category_name', 'longitude', 'latitude', 'prov_name', 'city_name', 'district_name', 'prov_code',
                  'city_code', 'district_code', 'merchant_desc', 'is_online', 'channel_id', 'channel_name', 'merchantchannel_set',
                  'settlement_amount_by_day', 'mall_applyment', 'is_enter_auth')

    def get_is_enter_auth(self, obj):
        if obj.is_mall == 0:
            check_merhant_channel = MerchantChannel.objects.filter(merchant_id=obj.id, channel_id=3)
            if not check_merhant_channel:
                return 0
            else:
                return 1
        else:
            return 0

    def get_mall_applyment(self, obj):
        data = {}
        data['is_mall'] = obj.is_mall
        data['is_mall_str'] = obj.get_is_mall_display()
        data['create_time'] = ''
        data['contract'] = ''
        data['applyment_state'] = ''
        data['applyment_state_str'] = ''
        data['audit_time'] = ''
        data['verify_state'] = ''
        data['verify_state_str'] = ''
        data['verify_user'] = ''
        data['verify_time'] = ''
        data['sign_url'] = ''
        data['reject_reason'] = ''
        try:
            mall_applyment = MerchantMallApplyment.objects.filter(merchant_id=obj.id, applyment_type=1).last()
            if mall_applyment:
                data['reject_reason'] = mall_applyment.reject_reason
                data['create_time'] = mall_applyment.create_time.strftime("%Y-%m-%d %H:%M:%S")
                data['contract'] = mall_applyment.contract.url
                data['applyment_state'] = mall_applyment.applyment_state
                data['applyment_state_str'] = mall_applyment.get_applyment_state_display()
                data['verify_state'] = mall_applyment.verify_state
                data['verify_state_str'] = mall_applyment.get_verify_state_display()
                if mall_applyment.verify_user:
                    data['verify_user'] = mall_applyment.verify_user.nickname
                # if mall_applyment.applyment_state == 4:
                #     result = check_sign_contract_result(obj.ruiyinxinMerchantID)
                #     if result['data']['sign_status'] == 3:
                #         obj.applyment_state = 1
                #         obj.verify_state = 1
                #         obj.save()
                #         mall_applyment.applyment_state = 1
                #         mall_applyment.audit_time = datetime.datetime.now()
                #         mall_applyment.save()
                # elif mall_applyment.applyment_state == 1:
                #     result = get_sign_contract_url(obj.ruiyinxinMerchantID)
                #     if result['result_code'] != 'fail':
                #         if result['data']['open_status'] == 2:
                #             if not mall_applyment.sign_url:
                #                 signUrl = result['data']['sign_url']
                #                 sign_url = make_qrcode1(obj.ruiyinxinMerchantID, signUrl, key=None)
                #                 mall_applyment.sign_url = sign_url
                #             mall_applyment.applyment_state = 2
                #             mall_applyment.save()
                #             obj.applyment_state = 2
                #             obj.save()
                #         elif result['data']['open_status'] == 3:
                #             mall_applyment.applyment_state = 3
                #             mall_applyment.reject_reason = result['data']['open_result']
                #             mall_applyment.save()
                #             obj.applyment_state = 3
                #             obj.save()
                data['sign_url'] = mall_applyment.sign_url.url
                data['audit_time'] = mall_applyment.audit_time.strftime("%Y-%m-%d %H:%M:%S")
                data['verify_time'] = mall_applyment.verify_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        return data

    def get_business_category_name(self, obj):
        try:
            return obj.business_category.name
        except:
            return ''

    def get_channel_name(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class MerchantEnterModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level = serializers.SerializerMethodField(read_only=True)
    manageruser = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEnter
        fields = ('id', 'create_time', 'level', 'manageruser')

    def get_manageruser(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class GoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    is_coupon_goods = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant', 'is_coupon_goods', 'order_species', 'order_species_str')

    def get_is_coupon_goods(self, obj):
        try:
            alidiscountcoupon_id = self.context.get('alidiscountcoupon_id', None)
            if alidiscountcoupon_id:
                check_available = AliDiscountCouponGoodsAvailable.objects.filter(goods_id=obj.id, alidiscountcoupon_id=alidiscountcoupon_id)
                if check_available:
                    return 1
                else:
                    return 0
            else:
                return 0
        except:
            return 0

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['name'] = ''
        data['short_name'] = ''
        data['id'] = ''
        try:
            merchant = obj.merchant
            data['name'] = merchant.name
            data['short_name'] = merchant.short_name
            data['id'] = merchant.id
        except:
            pass
        return data


class GoodsModifyApplymentModelSerializer(serializers.ModelSerializer):

    desc_detail = serializers.SerializerMethodField(read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    company_user = serializers.SerializerMethodField(read_only=True)
    applyment_type_str = serializers.CharField(source='get_applyment_type_display', read_only=True)

    class Meta:
        model = GoodsModifyApplyment
        fields = ('id', 'name', 'applyment_type', 'caption', 'desc_detail', 'price', 'market_price', 'default_image', 'goodsimage_set',
                  'manufacturer', 'specifications', 'applyment_type_str', 'company_user')

    def get_company_user(self, obj):
        try:
            return f'{obj.companyuser.nickname}({obj.companyuser.level.name})'
        except:
            return ''

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        try:
            return json.loads(obj.image_array)
        except:
            return obj.image_array


class GoodsRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    applyment = serializers.SerializerMethodField(read_only=True)
    reject_reason = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant_name', 'manufacturer', 'specifications', 'caption', 'goodsimage_set', 'desc_detail',
                  'market_price', 'merchant_id', 'applyment', 'reject_reason', 'goods_tag', 'order_type', 'order_type_str',
                  'is_group', 'group_price', 'group_order_num', 'group_limit_time', 'group_limit_type', 'order_species', 'order_species_str',
                  'proof', 'desc_pack')

    def get_reject_reason(self, obj):
        try:
            if obj.is_launched == 3:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=3).last()
                return applyment.reject_reason
            else:
                return ''
        except:
            return ''

    def get_applyment(self, obj):
        try:
            if obj.is_launched == 2:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=1).first()
                return GoodsModifyApplymentModelSerializer(applyment).data
            else:
                return {}
        except:
            return {}

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''


class LaunchedGoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    goodsinfo = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)

    class Meta:
        model = LaunchedGoods
        fields = ('id', 'create_time', 'point', 'goodsinfo', 'sales', 'level_name', 'is_launched', 'is_launched_str', 'stock')

    def get_goodsinfo(self, obj):
        data = {}
        data['default_image'] = ''
        data['name'] = ''
        data['category'] = ''
        data['equityID'] = ''
        data['merchant_name'] = ''
        data['sales'] = ''
        data['remain_stock'] = ''
        try:
            goods = obj.goods
            data['default_image'] = goods.default_image.url
            data['name'] = goods.name
            data['category'] = goods.category.name
            data['equityID'] = goods.equityID
            data['merchant_name'] = goods.merchant.name
            data['sales'] = goods.sales
            data['remain_stock'] = goods.remain_stock
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            if obj.is_self == 0:
                return obj.level.name
            else:
                return '自营'
        except:
            return ''


class ActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_name = serializers.SerializerMethodField(read_only=True)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ('id', 'create_time', 'activity_name', 'point', 'state', 'state_str', 'received_time', 'companyuser_nickname', 'level_name')

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.companyuser.level.name
        except:
            return ''


class ActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_name = serializers.SerializerMethodField(read_only=True)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    companyuser_level = serializers.SerializerMethodField(read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    customeruser_level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ('id', 'create_time', 'activity_name', 'point', 'state', 'state_str', 'received_time', 'companyuser_nickname', 'companyuser_level',
                  'customeruser_realname', 'customeruser_level')

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''

    def get_companyuser_level(self, obj):
        try:
            level = obj.companyuser.level
            return f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('-None', '')
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_customeruser_level(self, obj):
        try:
            level = obj.customer_user.level
            return f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('-None', '')
        except:
            return ''


class ActivityListSerializer(serializers.ModelSerializer):

    available_area = serializers.SerializerMethodField(read_only=True)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    remain_point = serializers.SerializerMethodField(read_only=True)
    progress = serializers.SerializerMethodField(read_only=True)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)

    class Meta:
        model = Activity
        fields = ('id', 'name', 'available_area', 'available_begin_time', 'available_end_time', 'max_point', 'distributed_point', 'remain_point', 'progress', 'activity_state',
                  'activity_state_str')

    def get_available_area(self, obj):
        try:
            level = obj.level
            return f'{level.prov_name}{level.city_name}{level.district_name}{level.branch_name}'.replace('None', '')
        except:
            return ''

    def get_remain_point(self, obj):
        try:
            return obj.max_point - obj.distributed_point
        except:
            return '0'

    def get_progress(self, obj):
        try:
            return f'{(obj.distributed_point / obj.max_point * 100).quantize(Decimal("0.00"))}%'
        except:
            return '0%'


class UserInfoSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    dimensionality_choices = serializers.SerializerMethodField(read_only=True)
    map_key = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'header', 'level_id', 'level_name', 'level', 'role_name', 'dimensionality_choices',
                  'map_key')

    def get_map_key(self, obj):
        return '5PLBZ-KIZC6-NCKSH-MOPXS-QP6OK-M4BIO'

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_dimensionality_choices(self, obj):
        try:
            dic1 = {
                0: {0: '信翔'},
                1: {1: '省公司'},
                2: {2: '市公司'},
                3: {3: '区县'},
                4: {4: '网点'},
            }
            level = obj.level.level
            data = []
            for i in range(level, 5):
                data.append(dic1[i])
            return data
        except:
            return []

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class OrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsModelSerializer(many=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    customer_user_mobile = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_point', 'use_time', 'total_price', 'level_name',
                  'customer_user_mobile', 'orderNum', 'order_species', 'order_species_str', 'freight', 'payment_time']

    def get_customer_user_mobile(self, obj):
        try:
            return obj.customer_user.mobile
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return f'{obj.level.name}(分店)'
        except:
            return '总店'


class OrderFundTransModelSerializer(serializers.ModelSerializer):

    trans_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = OrderFundTrans
        fields = ['id', 'trans_date', 'exchange_amount', 'status', 'status_str', 'identity', 'name', 'pay_fund_order_id', 'sub_msg']


class ExpressPlanModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = ExpressPlan
        fields = ('id', 'create_time', 'remark')


class ExpressModelSerializer(serializers.ModelSerializer):

    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    express_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expressplan_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'deliverystatus', 'deliverystatus_str', 'express_number', 'express_name', 'create_time', 'expressplan_set')

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_name(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''


class OrderAddressModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderAddress
        fields = ['id', 'receiver', 'place', 'mobile', 'province', 'city', 'district']


class RefundOrderInfoModelSerializer(serializers.ModelSerializer):

    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    user = serializers.SerializerMethodField(read_only=True)
    refund_status_str = serializers.CharField(source='get_refund_status_display', read_only=True)
    refund_type_str = serializers.CharField(source='get_refund_type_display', read_only=True)
    operator_role_str = serializers.CharField(source='get_operator_role_display', read_only=True)

    class Meta:
        model = RefundOrderInfo
        fields = ['id', 'refund_time', 'user', 'refund_order_id', 'refund_transaction_id', 'refund_money', 'refund_procedure_money', 'refund_status',
                  'refund_status_str', 'return_msg', 'refund_type', 'refund_type_str', 'operator_role', 'operator_role_str', 'remark']

    def get_user(self, obj):
        try:
            user = obj.user
            return user.nickname
        except Exception as e:
            return ''


class AfterSaleApplicationFormModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg',
                  'refund_time', 'reason', 'img_array', 'application_num']

    def get_reason(self, obj):
        try:
            return obj.reason.name
        except:
            return ''

    def get_img_array(self, obj):
        data = []
        try:
            queryset = AfterSaleApplicationFormImg.objects.filter(applicationform_id=obj.id)
            for query in queryset:
                data.append(query.img.url)
        except:
            pass
        return data


class OrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsModelSerializer(many=True)
    customer_user = serializers.SerializerMethodField(read_only=True)
    companyuser = serializers.SerializerMethodField(read_only=True)
    orderfundtrans_set = OrderFundTransModelSerializer(many=True)
    discount_amount = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    bill = serializers.SerializerMethodField(read_only=True)
    express_info = serializers.SerializerMethodField(read_only=True)
    orderaddress = serializers.SerializerMethodField(read_only=True)
    refundorderinfo_set = serializers.SerializerMethodField(read_only=True)
    after_sale = serializers.SerializerMethodField(read_only=True)
    group_data = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state_str', 'ordergoods_set', 'total_point', 'customer_user', 'companyuser',
                  'total_price', 'realpay_amount', 'discount_amount', 'orderfundtrans_set', 'state', 'use_time', 'orderNum', 'order_species', 'order_species_str',
                  'bill', 'express_info', 'orderaddress', 'refund_money', 'refundorderinfo_set', 'after_sale', 'freight', 'order_type', "order_type_str",
                  'group_data', 'payment_time']

    def get_after_sale(self, obj):
        try:
            after_sale = AfterSaleApplicationForm.objects.exclude(form_status=4).filter(order_id=obj.id).last()
            if after_sale:
                return AfterSaleApplicationFormModelSerializer(after_sale).data
            else:
                return {}
        except:
            return {}

    def get_group_data(self, obj):
        data = {}
        if obj.state in [13]:
            return data
        data['group_status'] = ''
        data['expired_time'] = ''
        data['account'] = ''
        data['people_list'] = []
        data['count'] = ''
        data['qrcode'] = ''
        data['share_pic'] = ''
        data['goods'] = {}
        data['is_self'] = 0
        try:
            group = obj.group
            if group:
                if group.group_status == 1:
                    cancel_group_order(group)
                if obj.state == 8:
                    data['group_status'] = 3
                else:
                    data['group_status'] = group.group_status if group.group_status != 0 else 4
                data['expired_time'] = group.expired_time.strftime("%Y-%m-%d %H:%M:%S")
                data['account'] = group.account
                goods = group.goods
                data['goods'] = {
                    "id": goods.id,
                    "price": goods.price,
                    "default_image": goods.default_image.url,
                    "name": goods.name,
                    "group_price": goods.group_price,
                }
                order_set = OrderInfo.objects.filter(group_id=obj.group_id, state__in=[15, 2, 8, 1, 3])
                count = group.group_order_num - len(order_set)
                data['count'] = count
                for order in order_set:
                    customeruservice = order.customeruservice
                    if customeruservice.avatar:
                        data['people_list'].append(customeruservice.avatar)
                    else:
                        data['people_list'].append('https://suppliera.postwork.cn/static/img/header.f38b3311.png')
                for i in range(count):
                    data['people_list'].append('https://jinjian.sutpay.cn/image/wyh_img128.png')
                if not group.qrcode:
                    redis_conn = get_redis_connection("scheme")
                    access_token = redis_conn.get('wyh_access_token')
                    if access_token is None:
                        access_token = redis_scheme_token_wyh()
                    else:
                        access_token = access_token.decode()
                    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                    body = {
                        "page": "pages/pro_detail_group/pro_detail_group",
                        "scene": f"id={goods.id}&account={group.account}",
                        "is_hyaline": True,
                    }
                    response = requests.post(url=url, json=body)
                    try:
                        if response.json()['errcode'] != 0:
                            access_token = redis_scheme_token_wyh()
                            url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                            response = requests.post(url=url, json=body)
                    except:
                        pass
                    reslut = response.content
                    market_code = pic_upload(reslut)
                    # merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                    # common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                    group.qrcode = market_code
                    group.save()
                    data['qrcode'] = f'https://circle.sutpay.cn/{market_code}'
                else:
                    data['qrcode'] = group.qrcode.url
                data['share_pic'] = group.share_pic.url
        except:
            pass
        return data

    def get_refundorderinfo_set(self, obj):
        try:
            refundorderinfo_set = obj.refundorderinfo_set.all()
            return RefundOrderInfoModelSerializer(refundorderinfo_set, many=True).data
        except:
            return []

    def get_orderaddress(self, obj):
        try:
            orderaddress = obj.orderaddress
            if orderaddress:
                return OrderAddressModelSerializer(orderaddress).data
            else:
                return {}
        except:
            return {}

    def get_express_info(self, obj):
        try:
            express_id_list = ExpressOrderRelevance.objects.filter(order_id=obj.id).values_list('express_id', flat=True)
            express_set = Express.objects.filter(id__in=list(express_id_list))
            return ExpressModelSerializer(express_set, many=True).data
        except:
            return []

    def get_discount_amount(self, obj):
        try:
            if obj.state in [12, 2, 3, 9, 6, 8, 5, 14]:
                return str(Decimal(obj.total_price - obj.realpay_amount - obj.total_point/100).quantize(Decimal('0.00')))
            elif obj.state == 1:
                return str(Decimal(obj.total_price - obj.payable_amount - obj.total_point/100).quantize(Decimal('0.00')))
            else:
                return '0.00'
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_customer_user(self, obj):
        data = {}
        data['realname'] = ''
        data['level'] = ''
        data['mobile'] = ''
        data['id'] = ''
        data['merchant'] = []
        data['is_merchant'] = 0
        try:
            customer_user = obj.customer_user
            level = customer_user.level
            data['id'] = customer_user.id
            data['realname'] = customer_user.realname
            data['mobile'] = customer_user.mobile
            merchant_set = Merchant.objects.filter(managermobile=customer_user.mobile)
            if level:
                data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            if merchant_set:
                data['is_merchant'] = 1
                merchant_list = []
                for merchant in merchant_set:
                    level = merchant.level
                    merchant_data = {}
                    merchant_data['id'] = merchant.id
                    merchant_data['business_no'] = merchant.wyfMerchantID
                    merchant_data['short_name'] = merchant.short_name
                    merchant_data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
                    merchant_list.append(merchant_data)
                data['merchant'] = merchant_list
            return data
        except Exception as e:
            pass
        return data

    def get_companyuser(self, obj):
        data = {}
        data['nickname'] = ''
        data['level'] = ''
        data['success_time'] = ''
        try:
            goodscoupons = obj.goodscoupons_set.all().order_by('-use_time').first()
            data['success_time'] = goodscoupons.use_time.strftime("%Y-%m-%d %H:%M:%S")
            companyuser = goodscoupons.use_user
            level = companyuser.level
            data['nickname'] = f'{companyuser.nickname}({companyuser.mobile})'
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            return data
        except:
            pass
        return data

    def get_bill(self, obj):
        data = {}
        data['id'] = ''
        data['receipts_time'] = ''
        data['bill_state'] = ''
        data['bill_state_str'] = ''
        data['settlement_time'] = ''
        data['settlement_record_id'] = ''
        try:
            bill = obj.bill
            data['id'] = bill.id
            data['receipts_time'] = bill.receipts_time.strftime("%Y-%m-%d")
            data['bill_state'] = bill.bill_state
            data['bill_state_str'] = bill.get_bill_state_display()
            data['settlement_time'] = bill.settlement_time.strftime("%Y-%m-%d")
            data['settlement_record_id'] = bill.settlement_record_id
        except:
            pass
        return data


class AliDiscountCouponListModelSerializer(serializers.ModelSerializer):

    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status_str = serializers.CharField(source='get_coupon_status_display', read_only=True)
    coupon_way_str = serializers.CharField(source='get_coupon_way_display', read_only=True)
    publish_time = serializers.SerializerMethodField(read_only=True)
    coupon_status = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    distribution_platform_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'coupon_type', 'coupon_type_str', 'activity_name', 'coupon_status', 'coupon_status_str', 'floor_amount',
                  'publish_time', 'max_number', 'send_count', 'remain_number', 'coupon_way', 'coupon_way_str', 'template_id', 'level_name',
                  'distribution_platform_id', 'distribution_platform_str']

    def get_distribution_platform_str(self, obj):
        try:
            return obj.distribution_platform.platform_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_coupon_status(self, obj):
        try:
            now_date = datetime.datetime.now()
            if obj.coupon_status in [1, 4]:
                if obj.publish_end_time < now_date:
                    obj.coupon_status = 2
                    obj.save()
                    return 2
            # elif obj.coupon_status == 3:
            #     if obj.publish_start_time < now_date:
            #         obj.coupon_status = 1
            #         obj.save()
            #         return 1
            return obj.coupon_status
        except:
            return obj.coupon_status

    def get_publish_time(self, obj):
        try:
            return f'{obj.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''


class AliDiscountCouponChannelCommonVoucherModelSerializer(serializers.ModelSerializer):

    discount_type_str = serializers.CharField(source='get_discount_type_display', read_only=True)
    bankcard_type_str = serializers.CharField(source='get_bankcard_type_display', read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)
    join_limit_by_user = serializers.SerializerMethodField(read_only=True)
    join_limit_by_bay = serializers.SerializerMethodField(read_only=True)
    distributed_limit_by_time_rules = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponChannelCommonVoucher
        fields = ['id', 'discount_type', 'discount_type_str', 'bankcard_type', 'bankcard_type_str', 'usetime_type', 'principal_name',
                  'join_limit_by_user', 'join_limit_by_bay', 'distributed_limit_by_time', 'distributed_limit_by_time_rules']

    def get_distributed_limit_by_time_rules(self, obj):
        data = []
        try:
            alidiscountcoupondistributedlimit_set = obj.alidiscountcoupondistributedlimit_set.all()
            for alidiscountcoupondistributedlimit in alidiscountcoupondistributedlimit_set:
                week_day_dict = {
                    '0': '周一',
                    '1': '周二',
                    '2': '周三',
                    '3': '周四',
                    '4': '周五',
                    '5': '周六',
                    '6': '周日',
                }
                weeks = ''
                for key,value in week_day_dict.items():
                    if key in alidiscountcoupondistributedlimit.weeks:
                        weeks += f'、{value}'
                data.append({
                    "weeks": f'每周 {weeks[1:]}',
                    "enable_time": f'{alidiscountcoupondistributedlimit.start_enable_time.strftime("%H:%M:%S")}-{alidiscountcoupondistributedlimit.end_enable_time.strftime("%H:%M:%S")}'
                })
        except:
            pass
        return data

    def get_usetime_type(self, obj):
        try:
            if obj.usetime_type == 2:
                return f'固定时间段{obj.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif obj.usetime_type == 3:
                return f'领取后立即生效有效时间{obj.invalid_day}天'
            else:
                return f'领取后次日凌晨生效有效时间{obj.invalid_day}天'
        except:
            return ''

    def get_join_limit_by_user(self, obj):
        try:
            if obj.join_limit_by_user == 1:
                return f'活动期间每个用户可参与{obj.join_limit_by_user_count}次'
            else:
                return '不限制'
        except:
            return ''

    def get_join_limit_by_bay(self, obj):
        try:
            if obj.join_limit_by_bay == 1:
                return f'每个用户每日可参与{obj.join_limit_by_bay_count}次'
            elif obj.join_limit_by_bay == 2:
                return f'每个用户每月可参与{obj.join_limit_by_bay_count}次'
            elif obj.join_limit_by_bay == 4:
                return f'每个用户每周可参与{obj.join_limit_by_bay_count}次'
            else:
                return '不限制'
        except:
            return ''


class AliDiscountCouponRetrieveModelSerializer(serializers.ModelSerializer):

    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status_str = serializers.CharField(source='get_coupon_status_display', read_only=True)
    coupon_way_str = serializers.CharField(source='get_coupon_way_display', read_only=True)
    publish_time = serializers.SerializerMethodField(read_only=True)
    alidiscountcouponchannelcommonvoucher = AliDiscountCouponChannelCommonVoucherModelSerializer()
    level = LevelModelSerializer()
    merchant_list = serializers.SerializerMethodField(read_only=True)
    platform = serializers.SerializerMethodField(read_only=True)
    can_remain_number = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    publish_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    publish_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    last_update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    developer_set = serializers.SerializerMethodField(read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    distribution_platform = serializers.SerializerMethodField(read_only=True)
    drawdown_platform = serializers.SerializerMethodField(read_only=True)
    is_max_number_by_day = serializers.SerializerMethodField(read_only=True)
    wyh_last_update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_check_identity = serializers.SerializerMethodField(read_only=True)
    ysh_alidiscountcoupon = serializers.SerializerMethodField(read_only=True)
    activity_zone_qrcode = serializers.SerializerMethodField(read_only=True)
    usage_scenario_str = serializers.CharField(source='get_usage_scenario_display', read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'coupon_type', 'coupon_type_str', 'activity_name', 'coupon_status', 'coupon_status_str', 'floor_amount',
                  'publish_time', 'max_number', 'send_count', 'remain_number', 'alidiscountcouponchannelcommonvoucher', 'level',
                  'is_union', 'is_white', 'available_merchants', 'coupon_way', 'coupon_way_str', 'activity_description', 'merchant_list',
                  'create_time', 'template_id', 'platform', 'publish_end_time', 'publish_start_time', 'transaction_minimum', 'amount',
                  'is_need_auth', 'can_remain_number', 'developer_set', 'last_update_time', 'create_user', 'remark', 'distribution_platform',
                  'distribution_platform_id', 'wyh_last_update_time', 'goods_tag', 'drawdown_platform', 'drawdown_platform_id', 'is_use_path', 'use_path', 'use_appid',
                  'is_self', 'max_number_by_day', 'is_max_number_by_day', 'is_check_identity', 'ysh_alidiscountcoupon', 'banner_long', 'banner_short',
                  'activity_zone_qrcode', 'is_psbc_card', 'product_no', 'is_keguan', 'pushEventIds', 'usage_scenario', 'usage_scenario_str']

    def get_is_use_path(self, obj):
        try:
            if obj.is_use_path:
                return obj.is_use_path
            else:
                return 0
        except:
            return 0

    def get_is_self(self, obj):
        try:
            if obj.is_self:
                return obj.is_self
            else:
                return 0
        except:
            return 0

    def get_activity_zone_qrcode(self, obj):
        try:
            if obj.coupon_channel == 2 and obj.goods_tag:
                if not obj.activity_zone_qrcode:
                    redis_conn = get_redis_connection("scheme")
                    access_token = redis_conn.get('wyh_access_token')
                    if access_token is None:
                        access_token = redis_scheme_token_wyh()
                    else:
                        access_token = access_token.decode()
                    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                    body = {
                        "page": "pages/coupon_pro_list/coupon_pro_list",
                        "scene": f"activity_id={obj.id}",
                        "is_hyaline": True
                    }
                    response = requests.post(url=url, json=body)
                    try:
                        if response.json()['errcode'] != 0:
                            access_token = redis_scheme_token_wyh()
                            url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                            response = requests.post(url=url, json=body)
                    except:
                        pass
                    reslut = response.content
                    activity_zone_qrcode = pic_upload(reslut)
                    obj.activity_zone_qrcode = activity_zone_qrcode
                    obj.save()
                    return f'https://circle.sutpay.cn/{activity_zone_qrcode}'
                else:
                    return obj.activity_zone_qrcode.url
            else:
                return ''
        except:
            return ''

    def get_ysh_alidiscountcoupon(self, obj):
        data = {}
        try:
            ysh_alidiscountcoupon = YSHAliDiscountCoupon.objects.filter(alidiscountcoupon_id=obj.id).first()
            if ysh_alidiscountcoupon:
                data['user'] = ysh_alidiscountcoupon.user.nickname
                data['create_time'] = ysh_alidiscountcoupon.create_time.strftime('%Y-%m-%d %H:%M:%S')
                data['equityId'] = ysh_alidiscountcoupon.equityId
                data['type'] = ysh_alidiscountcoupon.get_type_display()
                data['sourceDistCode'] = f'{ysh_alidiscountcoupon.sourceDistCode.name}({ysh_alidiscountcoupon.sourceDistCode.code})'
                data['usageType'] = ysh_alidiscountcoupon.get_usageType_display()
                data['verifyChannel'] = ysh_alidiscountcoupon.get_verifyChannel_display()
                data['environment'] = ysh_alidiscountcoupon.environment
                data['environment_str'] = ysh_alidiscountcoupon.get_environment_display()
                data['costAmount'] = Decimal(str(ysh_alidiscountcoupon.costAmount/100))
                contract = ysh_alidiscountcoupon.contract
                if contract:
                    data['taxRate'] = contract.taxRate
                    data['supplierCode'] = contract.supplierCode
                    data['supplierName'] = contract.supplierName
                    data['contractCode'] = contract.contractCode
                    data['contractName'] = contract.contractName
        except:
            pass
        return data

    def get_is_check_identity(self, obj):
        try:
            if obj.is_check_identity == 1:
                return 1
            else:
                return 0
        except:
            return 0

    def get_is_max_number_by_day(self, obj):
        try:
            if obj.max_number_by_day:
                return 1
            else:
                return 0
        except:
            return 0

    def get_drawdown_platform(self, obj):
        try:
            return obj.drawdown_platform.platform_name
        except:
            return ''

    def get_distribution_platform(self, obj):
        try:
            return obj.distribution_platform.platform_name
        except:
            return ''

    def get_create_user(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_developer_set(self, obj):
        data = []
        try:
            developer_set = AliDiscountCouponAPIRelation.objects.filter(alidiscountcoupon_id=obj.id)
            for developer in developer_set:
                user = developer.developer
                data.append({
                    'id': developer.id,
                    'account': user.account,
                    'nickname': user.nickname
                })
        except:
            pass
        return data

    def get_can_remain_number(self, obj):
        try:
            max_number__sum = obj.alidiscountcouponlevel_set.all().aggregate(Sum('max_number'))['max_number__sum']
            if max_number__sum:
                remain_number = obj.max_number - max_number__sum
            else:
                remain_number = obj.max_number
            return remain_number
        except:
            return 0

    def get_platform(self, obj):
        try:
            platform = obj.platform
            return f'{platform.name}({platform.mchid})'
        except:
            return ''

    def get_merchant_list(self, obj):
        data = []
        try:
            alidiscountcouponmerchant_set = obj.alidiscountcouponmerchant_set.all()
            if alidiscountcouponmerchant_set:
                alidiscountcouponmerchant_set = alidiscountcouponmerchant_set[:6]
                for alidiscountcouponmerchant in alidiscountcouponmerchant_set:
                    merchant = alidiscountcouponmerchant.merchant
                    data.append(f'{merchant.short_name}({merchant.wyfMerchantID})')
        except:
            pass
        return data

    def get_publish_time(self, obj):
        try:
            return f'{obj.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''


class AliDiscountCouponLevelListModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    wait_number = serializers.SerializerMethodField(read_only=True)
    unclaimed_number = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    p_wait_number = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'max_number', 'take_number', 'remain_number', 'wait_number', 'unclaimed_number', 'use_number',
                  'activity_name', 'p_max_number', 'p_take_number', 'p_remain_number', 'p_wait_number', 'p_unclaimed_number', 'p_use_number', 'common_qrcode']

    def get_wait_number(self, obj):
        try:
            wait_number = obj.receive_number - obj.use_number
            return wait_number
        except:
            return ''

    def get_p_wait_number(self, obj):
        try:
            p_wait_number = obj.p_receive_number - obj.p_use_number
            return p_wait_number
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.activity.activity_name
        except:
            return ''

    def get_unclaimed_number(self, obj):
        try:
            unclaimed_number = obj.take_number - obj.receive_number
            return unclaimed_number
        except:
            return ''

    def get_p_unclaimed_number(self, obj):
        try:
            p_unclaimed_number = obj.p_take_number - obj.p_receive_number
            return p_unclaimed_number
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class AliDiscountCouponLevelRetrieveModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    wait_number = serializers.SerializerMethodField(read_only=True)
    unclaimed_number = serializers.SerializerMethodField(read_only=True)
    can_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'max_number', 'take_number', 'remain_number', 'wait_number', 'unclaimed_number', 'use_number', 'can_number']

    def get_can_number(self, obj):
        data = {}
        data['max_number'] = 0
        data['min_number'] = 0
        try:
            activity = obj.activity
            max_number__sum = activity.alidiscountcouponlevel_set.all().aggregate(Sum('max_number'))['max_number__sum']
            if max_number__sum:
                remain_number = activity.max_number - max_number__sum
            else:
                remain_number = activity.max_number
            data['max_number'] = obj.max_number + remain_number
            data['min_number'] = obj.max_number - obj.remain_number
        except:
            pass
        return data

    def get_wait_number(self, obj):
        try:
            wait_number = obj.receive_number - obj.use_number
            return wait_number
        except:
            return ''

    def get_unclaimed_number(self, obj):
        try:
            unclaimed_number = obj.take_number - obj.receive_number
            return unclaimed_number
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class AliDiscountCouponLevelTreeModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_number = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    is_auth_str = serializers.CharField(source='get_is_auth_display', read_only=True)
    child_list = serializers.SerializerMethodField(read_only=True)
    p_wait_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'remain_number', 'activity_name',
                  'p_receive_number', 'p_remain_number', 'p_take_number', 'p_max_number', 'p_unclaimed_number', 'is_auth', 'is_auth_str',
                  'child_list', 'p_wait_number', 'p_use_number']

    def get_p_wait_number(self, obj):
        try:
            p_wait_number = obj.p_receive_number - obj.p_use_number
            return p_wait_number
        except:
            return ''

    def get_p_unclaimed_number(self, obj):
        try:
            p_unclaimed_number = obj.p_take_number - obj.p_receive_number
            return p_unclaimed_number
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.activity.activity_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''

    def get_child_list(self, obj):
        level = obj.level
        if level.level == 1:
            list_queryset = AliDiscountCouponLevel.objects.filter(child_set__parent_id=obj.id, level__level=2)
            return AliDiscountCouponLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 2:
            list_queryset = AliDiscountCouponLevel.objects.filter(child_set__parent_id=obj.id, level__level=3)
            return AliDiscountCouponLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 3:
            list_queryset = AliDiscountCouponLevel.objects.filter(child_set__parent_id=obj.id, level__level=4)
            return AliDiscountCouponLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 4:
            return []
        else:
            return []


class AliDiscountCouponInfoListModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'gmt_distributed', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'coupon_type', 'coupon_type_str', 'level_name', 'return_msg']

    def get_mobile(self, obj):
        if obj.alidiscountcoupon.coupon_way == 5 and obj.alidiscountcoupon.coupon_channel == 1:
            return obj.login_id
        else:
            return obj.mobile

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''


class AliDiscountCouponInfoRetrieveModelSerializer(serializers.ModelSerializer):

    gmt_use = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_undo = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    payout_info = serializers.SerializerMethodField(read_only=True)
    customeruser_idcode = serializers.SerializerMethodField(read_only=True)
    customeruser_identification_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'mobile', 'status', 'status_str', 'customeruser_realname', 'gmt_use', 'gmt_distributed', 'gmt_undo', 'payout_info', 'activity_info', 'order_id',
                  'out_biz_order', 'user_id', 'return_msg', 'customeruser_idcode', 'customeruser_identification_type']

    def get_activity_info(self, obj):
        data = {}
        data['activity_name'] = ''
        data['floor_amount'] = ''
        data['publish_time'] = ''
        data['usetime_type'] = ''
        data['coupon_type'] = ''
        data['coupon_type_str'] = ''
        try:
            activity = obj.alidiscountcoupon
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_type'] = activity.coupon_type
            data['floor_amount'] = activity.floor_amount
            data['publish_time'] = f'{activity.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{activity.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            data['activity_name'] = activity.activity_name
            if channelcommonvoucher.usetime_type == 2:
                data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            if channelcommonvoucher.join_limit_by_user == 1:
                data['join_limit_by_user'] = f'活动期间每个用户可参与{channelcommonvoucher.join_limit_by_user_count}次'
            else:
                data['join_limit_by_user'] = '不限制'
            if channelcommonvoucher.join_limit_by_bay == 1:
                data['join_limit_by_bay'] = f'每个用户每日可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            if channelcommonvoucher.join_limit_by_bay == 2:
                data['join_limit_by_bay'] = f'每个用户每月可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            elif channelcommonvoucher.join_limit_by_bay == 4:
                data['join_limit_by_bay'] = f'每个用户每周可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            else:
                data['join_limit_by_bay'] = '不限制'
        except:
            pass
        return data

    def get_payout_info(self, obj):
        data = {}
        data['alidiscountcoupon_id'] = ''
        data['level_name'] = ''
        data['companyuser_nickname'] = ''
        data['gmt_create'] = ''
        try:
            data['alidiscountcoupon_id'] = obj.alidiscountcoupon_id
            data['companyuser_nickname'] = obj.companyuser.nickname
            data['gmt_create'] = obj.gmt_create.strftime("%Y-%m-%d %H:%M:%S")
            data['level_name'] = obj.level.name
        except:
            pass
        return data

    def get_customeruser_realname(self, obj):
        try:
            if obj.customer_user:
                return obj.customer_user.realname
            else:
                return obj.customeruservice.realname
        except:
            return ''

    def get_customeruser_idcode(self, obj):
        try:
            if obj.customer_user:
                idcode = obj.customer_user.idcode
            else:
                idcode = obj.customeruservice.idcode
            return f'{idcode[:5]}****{idcode[-4:]}'
        except:
            return ''

    def get_customeruser_identification_type(self, obj):
        try:
            if obj.customer_user:
                return obj.customer_user.get_identification_type_display()
            else:
                return obj.customeruservice.get_identification_type_display()
        except:
            return ''


class MerchantBillListModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    bill_type_str = serializers.CharField(source='get_bill_type_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    account_info = serializers.SerializerMethodField(read_only=True)
    week_day = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    channel_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'account_info', 'settlement_time', 'week_day',
                  'order_count', 'channel_id', 'channel_name', 'bill_type', 'bill_type_str']

    def get_channel_name(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_week_day(self, obj):
        week_day_dict = {
            0: '星期一',
            1: '星期二',
            2: '星期三',
            3: '星期四',
            4: '星期五',
            5: '星期六',
            6: '星期日',
        }
        day = obj.receipts_time.weekday()
        return week_day_dict[day]

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['merchant_id'] = ''
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['wyfMerchantID'] = merchant.wyfMerchantID
            data['level_name'] = level.name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['merchant_id'] = merchant.id
        except:
            pass
        return data

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class MerchantBillRetrieveModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    account_info = serializers.SerializerMethodField(read_only=True)
    # payable_amount = serializers.SerializerMethodField(read_only=True)
    settlement_info = serializers.SerializerMethodField(read_only=True)
    fail_reason = serializers.SerializerMethodField(read_only=True)
    bill_type_str = serializers.CharField(source='get_bill_type_display', read_only=True)
    other_amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'settlement_time', 'order_count', 'account_info',
                  'settlement_info', 'fail_reason', 'bill_type', 'bill_type_str', 'commission', 'amount', 'other_amount', 'other_commission', 'other_settlement_amount']

    def get_other_amount(self, obj):
        try:
            yesterday = datetime.datetime.now() + datetime.timedelta(days=-1)
            if obj.other_amount == None and obj.receipts_time < yesterday:
                url = 'https://manage.gdwxyf.com/internal/searchorders.do'
                body = {
                    "shopId": obj.merchant.wyfMerchantID,
                    "start": obj.receipts_time.strftime("%Y-%m-%d 00:00:00"),
                    "end": obj.receipts_time.strftime("%Y-%m-%d 23:59:59"),
                    "branchId": "2",
                    "account": "gdyouzheng",
                    "orderStatus": "all"
                }
                response = requests.post(url=url, data=body)
                result = response.json()['showList']
                other_amount = Decimal('0')
                other_commission = Decimal('0')
                other_settlement_amount = Decimal('0')
                for i in result:
                    if 'subOpenid' in i:
                        if 'omjwf4' != i['subOpenid'][:6]:
                            other_amount += Decimal(i['totalFee'])
                            other_commission += Decimal(i['commissionPay'])
                            other_settlement_amount += Decimal(i['paidout'])
                    else:
                        if i['device'] != '微邮惠商圈':
                            other_amount += Decimal(i['totalFee'])
                            other_commission += Decimal(i['commissionPay'])
                            other_settlement_amount += Decimal(i['paidout'])
                obj.other_amount = other_amount
                obj.other_commission = other_commission
                obj.other_settlement_amount = other_settlement_amount
                obj.save()
                return obj.other_amount
            else:
                return obj.other_amount
        except:
            return ''

    def get_fail_reason(self, obj):
        return ''

    def get_settlement_info(self, obj):
        data = []
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                merchantsettlementrecord_data = {}
                merchantsettlementrecord = merchantbillsettlementrecord.settlement_record
                merchantsettlementrecord_data['settlement_time'] = merchantsettlementrecord.settlement_time.strftime('%Y-%m-%d')
                merchantsettlementrecord_data['settlement_id'] = merchantsettlementrecord.id
                merchantsettlementrecord_data['settlement_amount'] = merchantsettlementrecord.amount
                merchantsettlementrecord_data['status'] = merchantsettlementrecord.status
                merchantsettlementrecord_data['status_str'] = merchantsettlementrecord.get_status_display()
                data.append(merchantsettlementrecord_data)
        except:
            pass
        return data

    # def get_payable_amount(self, obj):
    #     try:
    #         bill_state = obj.bill_state
    #         if bill_state == 3:
    #             return obj.settlement_record.amount
    #         else:
    #             return 0
    #     except:
    #         return 0

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level'] = ''
        data['merchant_id'] = ''
        try:
            data['merchant_name'] = obj.merchant.name
            data['wyfMerchantID'] = obj.merchant.wyfMerchantID
            data['merchant_id'] = obj.merchant_id
            level = obj.merchant.level
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class GoodsCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = ['id', 'name', 'icon']


class MerchantBusinessCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantBusinessCategory
        fields = ['id', 'name']


class EnterLvelModelSerializer(serializers.ModelSerializer):

    contact = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Level
        fields = ['id', 'city_name', 'district_name', 'branch_name', 'account', 'contact']

    def get_contact(self, obj):
        data = {}
        merchant = self.context.get('merchant', None)
        data['managerName'] = merchant.managerName
        data['managermobile'] = merchant.managermobile
        try:
            enterlevel = MerchantEnter.objects.filter(level_id=obj.id, merchant_id=merchant.id).first()
            if enterlevel:
                data['managerName'] = enterlevel.managerName
                data['managermobile'] = enterlevel.managermobile
        except:
            pass
        return data


class ChannelModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Channel
        fields = ['id', 'mchid', 'name']


class CashActivityListModelSerializer(serializers.ModelSerializer):

    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    rule = serializers.SerializerMethodField(read_only=True)
    activity_state = serializers.SerializerMethodField(read_only=True)
    available_begin_time = serializers.DateTimeField(format="%Y.%m.%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y.%m.%d %H:%M:%S", required=False)
    publish_time = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivity
        fields = ['id', 'name', 'activity_type', 'activity_type_str', 'activity_state', 'activity_state_str', 'max_amount', 'remain_amount', 'available_begin_time', 'available_end_time', 'rule', 'publish_time',
                  'level_name']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_publish_time(self, obj):
        try:
            return f'{obj.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''

    def get_activity_state(self, obj):
        try:
            now_date = datetime.datetime.now()
            if obj.activity_state != 4 and obj.available_end_time < now_date:
                obj.activity_state = 4
                obj.save()
                return 4
            return obj.activity_state
        except:
            return obj.activity_state

    def get_rule(self, obj):
        try:
            if obj.activity_type in [1, 4, 8]:
                return f'{obj.min_distributed_amount}-{obj.max_distributed_amount}'
            else:
                cashactivityrule_set = obj.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'{cashactivityrule.amount},'
                return result[:-1]
        except:
            return ''


class CashActivityRuleModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = CashActivityRule
        fields = ['id', 'amount', 'probability']


class CashActivityRetrieveModelSerializer(serializers.ModelSerializer):

    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    is_check_identity_str = serializers.CharField(source='get_is_check_identity_display', read_only=True)
    rule = serializers.SerializerMethodField(read_only=True)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level = serializers.SerializerMethodField(read_only=True)
    can_remain_amount = serializers.SerializerMethodField(read_only=True)
    cashactivityrule_set = CashActivityRuleModelSerializer(many=True)
    developer_set = serializers.SerializerMethodField(read_only=True)
    id = serializers.SerializerMethodField(read_only=True)
    wx_channel = serializers.SerializerMethodField(read_only=True)
    ali_channel = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivity
        fields = ['id', 'name', 'activity_type', 'activity_type_str', 'activity_state', 'activity_state_str', 'max_amount', 'remain_amount', 'available_begin_time', 'available_end_time', 'rule',
                  'activity_description', 'create_time', 'level', 'can_remain_amount', 'is_max_amount_by_day', 'is_max_amount_by_user_by_day', 'is_max_amount_by_user',
                  'is_max_amount_by_customeruser', 'max_amount_by_day', 'max_amount_by_user_by_day', 'max_amount_by_user', 'max_amount_by_customeruser', 'cashactivityrule_set',
                  'is_need_auth', 'is_check_identity', 'is_check_identity_str', 'developer_set', 'wx_channel', 'ali_channel', 'wx_channel_id', 'ali_channel_id',
                  'is_push_ylx', 'is_psbc_card', 'is_wechat', 'is_white', 'is_limit_white', 'white_accout', 'is_merchant', 'repeat_business_no_count',
                  'is_keguan', 'pushEventIds', 'is_white_merchant']

    def get_ali_channel(self, obj):
        try:
            return f'{obj.ali_channel.name}({obj.ali_channel.mchid})'
        except:
            return ''

    def get_wx_channel(self, obj):
        try:
            return f'{obj.wx_channel.name}({obj.wx_channel.mchid})'
        except:
            return ''

    def get_id(self, obj):
        try:
            return obj.activity_id
        except:
            return ''

    def get_developer_set(self, obj):
        data = []
        try:
            developer_set = CashActivityAPIRelation.objects.filter(cashactivity_id=obj.id)
            for developer in developer_set:
                user = developer.developer
                data.append({
                    'id': developer.id,
                    'account': user.account,
                    'nickname': user.nickname
                })
        except:
            pass
        return data

    def get_can_remain_amount(self, obj):
        try:
            max_amount__sum = obj.cashactivitylevel_set.all().aggregate(Sum('max_amount'))['max_amount__sum']
            if max_amount__sum:
                remain_amount = obj.max_amount - max_amount__sum
            else:
                remain_amount = obj.max_amount
            return remain_amount
        except:
            return 0

    def get_rule(self, obj):
        try:
            if obj.activity_type in [1, 4, 8]:
                return f'{obj.min_distributed_amount}-{obj.max_distributed_amount}'
            else:
                cashactivityrule_set = obj.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'{cashactivityrule.amount},'
                return result[:-1]
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class CashActivityLevelListModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    is_auth_str = serializers.CharField(source='get_is_auth_display', read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'level_type', 'level_name', 'remain_amount', 'activity_name',
                  'p_receive_amount', 'p_remain_amount', 'p_take_amount', 'p_max_amount', 'p_unclaimed_amount', 'is_auth', 'is_auth_str']

    def get_p_unclaimed_amount(self, obj):
        try:
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            return p_unclaimed_amount
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return '网点'
            else:
                return '信翔'
        except:
            return ''


class CashActivityLevelRetrieveModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    can_amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'level_type', 'level_name', 'max_amount', 'take_amount', 'remain_amount', 'unclaimed_amount', 'receive_amount', 'activity_name', 'can_amount']

    def get_can_amount(self, obj):
        data = {}
        data['max_amount'] = 0
        data['min_amount'] = 0
        try:
            cash_activity = obj.cash_activity
            max_amount__sum = cash_activity.cashactivitylevel_set.all().aggregate(Sum('max_amount'))['max_amount__sum']
            if max_amount__sum:
                remain_amount = cash_activity.max_amount - max_amount__sum
            else:
                remain_amount = cash_activity.max_amount
            data['max_amount'] = obj.max_amount + remain_amount
            data['min_amount'] = obj.max_amount - obj.remain_amount
        except:
            pass
        return data

    def get_unclaimed_amount(self, obj):
        try:
            unclaimed_amount = obj.take_amount - obj.receive_amount
            return unclaimed_amount
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return '网点'
            else:
                return '信翔'
        except:
            return ''


class CashActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    activity_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    city_name = serializers.SerializerMethodField(read_only=True)
    district_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'mobile', 'state', 'state_str', 'received_time', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'activity_type', 'activity_type_str', 'level_name', 'amount', 'city_name', 'district_name', 'merchant']

    def get_merchant(self, obj):
        data = {}
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['level_name'] = ''
        data['is_white'] = ''
        try:
            white = CashActivityDataWhiteTable.objects.filter(activitydata_id=obj.id).first()
            if white:
                data['business_no'] = white.business_no
                data['is_white'] = str(white.is_white_table)
                if white.is_white_table == 0:
                    merchant = Merchant.objects.filter(wyfMerchantID=white.business_no).first()
                    data['merchant_name'] = merchant.name
                    data['level_name'] = merchant.level.name
        except:
            pass
        return data

    def get_city_name(self, obj):
        try:
            return obj.level.city_name
        except:
            return ''

    def get_district_name(self, obj):
        try:
            return obj.level.district_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_activity_type_str(self, obj):
        try:
            return obj.cash_activity.get_activity_type_display()
        except:
            return ''

    def get_activity_type(self, obj):
        try:
            return obj.cash_activity.activity_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_mobile(self, obj):
        try:
            if obj.customer_user:
                return obj.customer_user.mobile
            elif obj.customeruservice:
                return obj.customeruservice.mobile
            else:
                return obj.mobile
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''


class CashActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    activity_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    mchid = serializers.SerializerMethodField(read_only=True)
    city_name = serializers.SerializerMethodField(read_only=True)
    district_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'mobile', 'state', 'state_str', 'received_time', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'activity_type', 'activity_type_str', 'level_name', 'amount', 'expired_time', 'payment_no', 'cash_activity_id', 'return_msg', 'mchid', 'payeeFullName',
                  'city_name', 'district_name']

    def get_city_name(self, obj):
        try:
            return obj.level.city_name
        except:
            return ''

    def get_district_name(self, obj):
        try:
            return obj.level.district_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_mchid(self, obj):
        try:
            channel = obj.channel
            if channel:
                return f'{channel.name}({channel.mchid})'
            else:
                return ''
            # if obj.mchid == '1486198522':
            #     return '信翔商户(1486198522)'
            # elif obj.mchid == '1571060401':
            #     return '信亨商户(1571060401)'
            # elif obj.mchid == 'wx':
            #     return '信翔商户(1486198522)'
            # elif obj.mchid == 'alipay':
            #     return '信翔支付宝服务商(2088631976752358)'
            # else:
            #     return ''
        except:
            return ''

    def get_activity_type_str(self, obj):
        try:
            return obj.cash_activity.get_activity_type_display()
        except:
            return ''

    def get_activity_type(self, obj):
        try:
            return obj.cash_activity.activity_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_mobile(self, obj):
        try:
            if obj.customer_user:
                return obj.customer_user.mobile
            elif obj.customeruservice:
                return obj.customeruservice.mobile
            else:
                return obj.mobile
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''


class CashActivityLevelStatisticalModelSerializer(serializers.ModelSerializer):

    child_list = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    level_type = serializers.SerializerMethodField(read_only=True)
    amountData = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['level_name', 'level_type', 'p_max_amount', 'p_take_amount', 'p_remain_amount', 'amountData', 'child_list']

    def get_level_name(self, obj):
        return obj.level.name

    def get_level_type(self, obj):
        level = obj.level.level
        if level == 1:
            return '省公司'
        elif level == 2:
            return '市公司'
        elif level == 3:
            return '区县'
        elif level == 4:
            return '网点'
        else:
            return '信翔'

    def get_amountData(self, obj):
        data = [
            {"name": "已派发", "value": obj.p_take_amount},
            {"name": "剩余额度", "value": obj.p_remain_amount},
            {"name": "总额度", "value": obj.p_max_amount}
        ]
        return data

    def get_child_list(self, obj):
        level = obj.level
        if level.level == 1:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=2)
            return CashActivityLevelStatisticalModelSerializer(list_queryset, many=True).data
        elif level.level == 2:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=3)
            return CashActivityLevelStatisticalModelSerializer(list_queryset, many=True).data
        elif level.level == 3:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=4)
            return CashActivityLevelStatisticalModelSerializer(list_queryset, many=True).data
        elif level.level == 4:
            return []
        else:
            return []


class CashActivityLevelTreeModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    is_auth_str = serializers.CharField(source='get_is_auth_display', read_only=True)
    child_list = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'level_type', 'level_name', 'remain_amount', 'activity_name',
                  'p_receive_amount', 'p_remain_amount', 'p_take_amount', 'p_max_amount', 'p_unclaimed_amount', 'is_auth', 'is_auth_str',
                  'child_list']

    def get_p_unclaimed_amount(self, obj):
        try:
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            return p_unclaimed_amount
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''

    def get_child_list(self, obj):
        level = obj.level
        if level.level == 1:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=2)
            return CashActivityLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 2:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=3)
            return CashActivityLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 3:
            list_queryset = CashActivityLevel.objects.filter(child_set__parent_id=obj.id, level__level=4)
            return CashActivityLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 4:
            return []
        else:
            return []


class CashActivityLevelRecordModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    operation_type_str = serializers.CharField(source='get_operation_type_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    user_nickname = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CashActivityLevelRecord
        fields = ['id', 'level_name', 'operation_type', 'operation_type_str', 'amount', 'remain_amount', 'create_time', 'remark', 'user_nickname', 'activity_type', 'activity_type_str']

    def get_level_name(self, obj):
        try:
            return obj.activity_level.level.name
        except:
            return ''

    # def get_amount(self, obj):
    #     try:
    #         if obj.operation_type in [1, 3, 6]:
    #             return obj.amount
    #         else:
    #             return -obj.amount
    #     except:
    #         return ''

    def get_user_nickname(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''


class UpdateStockUsableMerchantListModelSerializer(serializers.ModelSerializer):

    user_nickname = serializers.SerializerMethodField(read_only=True)
    remark = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    wx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    ylx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    apply_state_str = serializers.CharField(source='get_apply_state_display', read_only=True)

    class Meta:
        model = UpdateStockUsableMerchant
        fields = ['id', 'user_nickname', 'file', 'remark', 'create_time', 'wx_is_enter', 'wx_is_enter_str', 'ylx_is_enter', 'ylx_is_enter_str',
                  'max_number', 'wx_entry_number', 'ylx_entry_number', 'apply_state', 'apply_state_str', 'logs_file']

    def get_remark(self, obj):
        if obj.apply_state == 3:
            return obj.return_msg
        else:
            return obj.remark

    def get_user_nickname(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''


class UpdateStockUsableMerchantRetrieveModelSerializer(serializers.ModelSerializer):

    user_nickname = serializers.SerializerMethodField(read_only=True)
    remark = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    wx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    ylx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    apply_state_str = serializers.CharField(source='get_apply_state_display', read_only=True)
    alidiscountcoupon = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = UpdateStockUsableMerchant
        fields = ['id', 'user_nickname', 'file', 'remark', 'create_time', 'wx_is_enter', 'wx_is_enter_str', 'ylx_is_enter', 'ylx_is_enter_str',
                  'max_number', 'wx_entry_number', 'ylx_entry_number', 'apply_state', 'apply_state_str', 'alidiscountcoupon', 'line_number']

    def get_alidiscountcoupon(self, obj):
        data = {}
        data['alidiscountcoupon_id'] = ''
        data['activity_name'] = ''
        data['floor_amount'] = ''
        data['amount'] = ''
        data['transaction_minimum'] = ''
        try:
            alidiscountcoupon = obj.alidiscountcoupon
            data['alidiscountcoupon_id'] = alidiscountcoupon.id
            data['activity_name'] = alidiscountcoupon.activity_name
            data['floor_amount'] = alidiscountcoupon.floor_amount
            data['amount'] = alidiscountcoupon.amount
            data['transaction_minimum'] = alidiscountcoupon.transaction_minimum
        except:
            pass
        return data

    def get_remark(self, obj):
        if obj.apply_state == 3:
            return obj.return_msg
        else:
            return obj.remark

    def get_user_nickname(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''


class AliDiscountCouponMerchantModelSerializer(serializers.ModelSerializer):

    merchant = MerchantListModelSerializer()
    channel = serializers.SerializerMethodField(read_only=True)
    # last_update_time = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponMerchant
        fields = ['id', 'sub_mchid', 'merchant', 'channel_id', 'channel']

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''


class WaivePaymentActivityModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    is_repeat_str = serializers.CharField(source='get_is_repeat_display', read_only=True)
    activity_state = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentActivity
        fields = ['id', 'activity_name', 'available_begin_time', 'available_end_time', 'desc', 'activity_state', 'activity_state_str', 'description',
                  'receive_amount', 'join_number', 'create_time', 'is_repeat', 'is_repeat_str']

    def get_activity_state(self, obj):
        try:
            available_end_time = obj.available_end_time
            if available_end_time < datetime.datetime.now():
                obj.activity_state = 4
                obj.save()
            return obj.activity_state
        except:
            return obj.activity_state


class WaivePaymentAdvanceModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    operate_type_str = serializers.CharField(source='get_operate_type_display', read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    activate_user = serializers.SerializerMethodField(read_only=True)
    trade_time_begin = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    trade_time_end = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activate_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = WaivePaymentAdvance
        fields = ['id', 'create_time', 'activity_state', 'activity_state_str', 'remark',
                  'file', 'create_user', 'payment_state', 'payment_state_str', 'trade_time_begin',
                  'trade_time_end', 'activate_time', 'activate_user', 'name', 'operate_type', 'operate_type_str',
                  'join_number']

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''

    def get_activate_user(self, obj):
        try:
            return obj.activate_user.nickname
        except:
            return ''


class WaivePaymentMerchantInfoModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'short_name', 'level']

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class WaivePaymentMerchantListModelSerializer(serializers.ModelSerializer):

    # create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    # received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = WaivePaymentMerchantInfoModelSerializer()
    # amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WaivePaymentMerchant
        fields = ['id', 'business_no', 'payment_state', 'payment_state_str', 'company_mobile', 'amount', 'merchant']

    # def get_amount(self, obj):
    #     try:
    #         if obj.payment_state in [1, 2, 3]:
    #             return obj.amount
    #         return ''
    #     except:
    #         return ''


class WaivePaymentMerchantRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_state_str = serializers.CharField(source='get_payment_state_display', read_only=True)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    available_time = serializers.SerializerMethodField(read_only=True)
    merchant = WaivePaymentMerchantInfoModelSerializer()

    class Meta:
        model = WaivePaymentMerchant
        fields = ['id', 'create_time', 'business_no', 'payment_state', 'payment_state_str', 'company_mobile',
                  'received_time', 'payment_no', 'return_msg', 'partner_trade_no', 'account', 'name', 'payment_time',
                  'amount', 'merchant', 'activity_name', 'available_time']

    def get_activity_name(self, obj):
        try:
            return obj.waivepaymentactivity.activity_name
        except:
            return ''

    def get_available_time(self, obj):
        try:
            return f'{obj.waivepaymentactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.waivepaymentactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''

    # def get_amount(self, obj):
    #     try:
    #         if obj.payment_state in [1, 2, 3]:
    #             return obj.amount
    #         return ''
    #     except:
    #         return ''


class WaivePaymentOrderModelSerializer(serializers.ModelSerializer):

    trade_time_end = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    trade_type_str = serializers.CharField(source='get_trade_type_display', read_only=True)
    is_hit_str = serializers.CharField(source='get_is_hit_display', read_only=True)

    class Meta:
        model = WaivePaymentOrder
        fields = ['id', 'order_no', 'trade_no', 'trade_type', 'trade_type_str', 'rate_money',
                  'trade_money', 'settlement_money', 'trade_time_end', 'channel', 'is_hit', 'is_hit_str']


class BlackTableModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = BlackTable
        fields = ['id', 'stock_id']


class MerchantSettlementRecordListModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_time = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_time', 'merchant', 'level_name', 'is_bind',
                  'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_time(self, obj):
        data = ''
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                data += f"{merchantbillsettlementrecord.bill.receipts_time.strftime('%Y-%m-%d')},"
        except:
            pass
        if ',' in data:
            data = data[:-1]
        return data


class MerchantSettlementRecordRetrieveModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_data = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_data', 'merchant', 'level_name',
                  'account_name', 'account_bank', 'account_number', 'fail_reason', 'is_bind', 'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
            data['level'] =  f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_data(self, obj):
        data = {}
        try:
            bill_list = []
            time_str = ''
            order_num = 0
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                bill_data = {}
                bill = merchantbillsettlementrecord.bill
                receipts_time = bill.receipts_time.strftime('%Y-%m-%d')
                time_str += f"{receipts_time},"
                orderinfo_set = bill.orderinfo_set.all()
                if orderinfo_set:
                    order_sum = orderinfo_set.count()
                    payable_settled_amount__sum = orderinfo_set.aggregate(Sum('payable_settled_amount'))['payable_settled_amount__sum']
                    order_num += order_sum
                    bill_data['order_count'] = order_sum
                    bill_data['payable_settled_amount__sum'] = payable_settled_amount__sum
                    bill_data['receipts_time'] = receipts_time
                    bill_data['bill_id'] = bill.id
                    bill_list.append(bill_data)
            if ',' in time_str:
                time_str = time_str[:-1]
            data['receipts_time'] = time_str
            data['order_count'] = order_num
            data['array'] = bill_list
        except:
            pass
        return data


class SYOrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    repeal_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    order_status_str = serializers.CharField(source='get_order_status_display', read_only=True)

    class Meta:
        model = SYOrderInfo
        fields = ['id', 'create_time', 'order_status', 'order_status_str', 'shop_id', 'money', 'context', 'channel', 'repeal_time']


class SYOrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    repeal_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    order_status_str = serializers.CharField(source='get_order_status_display', read_only=True)

    class Meta:
        model = SYOrderInfo
        fields = ['id', 'create_time', 'order_status', 'order_status_str', 'shop_id', 'money', 'context', 'channel', 'repeal_time']


class CustomizeActivityListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    prize_type_str = serializers.SerializerMethodField(read_only=True)
    prize_type_array = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivity
        fields = ['id', 'create_time', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time',
                  'activity_type', 'activity_type_str', 'prize_type_str', 'prize_type', 'activity_name', 'level_name', 'join_user_count',
                  'prize_type_array']

    def get_prize_type_array(self, obj):
        data = []
        try:
            PRIZE_TYPE_CHOICES = {
                "1": {"prize_type": 1, "prize_type_str": "支付宝代金券"},
                "2": {"prize_type": 2, "prize_type_str": "微信代金券"},
                "3": {"prize_type": 3, "prize_type_str": "微信鼓励金"},
                "5": {"prize_type": 5, "prize_type_str": "积分"},
                "6": {"prize_type": 6, "prize_type_str": "支付宝鼓励金"},
                "7": {"prize_type": 7, "prize_type_str": "商家券"},
                "8": {"prize_type": 8, "prize_type_str": "美团代金券"},
            }
            prize_type = obj.prize_type
            for key,value in PRIZE_TYPE_CHOICES.items():
                if key in prize_type:
                    data.append(value)
        except:
            pass
        return data

    def get_prize_type_str(self, obj):
        try:
            data = obj.prize_type.replace('1', '支付宝代金券').replace('2', '微信代金券').replace('3', '微邮惠礼包')
            return data
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class CustomizeActivityRulesListModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityRules
        fields = ['id', 'prize_type', 'prize_type_str', 'activity_info', 'count']

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['available_begin_time'] = ''
        data['available_end_time'] = ''
        data['max'] = ''
        data['remain'] = ''
        data['take'] = ''
        try:
            prize_type = obj.prize_type
            if prize_type in [1, 2, 7, 8]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = alidiscountcoupon.id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['available_begin_time'] = alidiscountcoupon.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = alidiscountcoupon.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = alidiscountcoupon.max_number
                data['remain'] = alidiscountcoupon.remain_number
                data['take'] = alidiscountcoupon.send_count
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = cashactivity.id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['available_begin_time'] = cashactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = cashactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = cashactivity.max_amount
                data['remain'] = cashactivity.remain_amount
                data['take'] = cashactivity.take_amount
        except:
            pass
        return data


class CustomizeActivityRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    is_need_auth_str = serializers.CharField(source='get_is_need_auth_display', read_only=True)
    is_white_str = serializers.CharField(source='get_is_white_display', read_only=True)
    prize_type_str = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    customizeactivityrules_set = CustomizeActivityRulesListModelSerializer(many=True)
    prize_type_array = serializers.SerializerMethodField(read_only=True)
    drawdown_platform_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivity
        fields = ['id', 'create_time', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time',
                  'activity_type', 'activity_type_str', 'prize_type_str', 'prize_type', 'activity_name', 'level', 'join_user_count',
                  'is_need_auth', 'is_need_auth_str', 'lucky_count_by_user', 'activity_description', 'customizeactivityrules_set',
                  'is_white', 'is_white_str', 'prize_type_array', 'max_number', 'take_number', 'remain_number', 'drawdown_platform_id',
                  'drawdown_platform_name']

    def get_drawdown_platform_name(self, obj):
        try:
            return obj.drawdown_platform.platform_name
        except:
            return ''

    def get_prize_type_array(self, obj):
        data = []
        try:
            PRIZE_TYPE_CHOICES = {
                "1": {"prize_type": 1, "prize_type_str": "支付宝代金券"},
                "2": {"prize_type": 2, "prize_type_str": "微信代金券"},
                "3": {"prize_type": 3, "prize_type_str": "微信鼓励金"},
                "5": {"prize_type": 5, "prize_type_str": "积分"},
                "6": {"prize_type": 6, "prize_type_str": "支付宝鼓励金"},
                "7": {"prize_type": 7, "prize_type_str": "商家券"},
                "8": {"prize_type": 8, "prize_type_str": "美团代金券"},
            }
            prize_type = obj.prize_type
            for key,value in PRIZE_TYPE_CHOICES.items():
                if key in prize_type:
                    data.append(value)
        except:
            pass
        return data

    def get_prize_type_str(self, obj):
        try:
            data = obj.prize_type.replace('1', '支付宝代金券').replace('2', '微信代金券').replace('3', '微邮惠礼包')
            return data
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class CustomizeActivityLevelListModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityLevel
        fields = ['id', 'level_type', 'level_name', 'activity_name', 'max_number', 'take_number', 'remain_number', 'receive_number']

    def get_activity_name(self, obj):
        try:
            return obj.customizeactivity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class CustomizeActivityFlipCARDSListModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_info', 'open_time', 'win_type', 'win_type_str',
                  'received_time', 'open_time', 'level_name']

    def get_business_form(self, obj):
        data = {}
        try:
            if obj.customizeactivity.is_business_form == 1:
                business_form = obj.customizeactivitybusinessform
                data['business_name'] = business_form.business_name
                data['business_account'] = business_form.business_account
                data['business_amount'] = business_form.business_amount
                data['business_type'] = business_form.business_type
                data['business_type_str'] = business_form.get_business_type_display()
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_customercser_mobile(self, obj):
        try:
            return obj.mobile
        except:
            return ''

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.win_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = obj.alidiscountcouponinfo_id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['amount'] = alidiscountcoupon.amount
            elif prize_type == 5:
                data['id'] = ''
                data['activity_name'] = f'{obj.point} 积分'
                data['activity_id'] = ''
                data['rule'] = f'{obj.point} 积分'
                data['amount'] = f''
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = obj.cashactivitydata_id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['amount'] = obj.cashactivitydata.amount
        except:
            pass
        return data


class CustomizeActivityFlipCARDSRetrieveModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    activity_detail = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    business_form = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_info', 'open_time', 'win_type', 'win_type_str',
                  'received_time', 'open_time', 'level', 'business_form', 'return_msg', 'activity_detail']

    def get_activity_detail(self, obj):
        data = []
        if obj.win_type == 8:
            detail_set = CustomizeActivityFlipCARDSDetail.objects.filter(flipcard_id=obj.id)
            for detail in detail_set:
                data.append(AliDiscountCouponInfoListModelSerializer(detail.alidiscountcouponinfo).data)
        return data

    def get_business_form(self, obj):
        data = {}
        try:
            if obj.customizeactivity.is_business_form == 1:
                business_form = obj.customizeactivitybusinessform
                data['business_name'] = business_form.business_name
                data['business_account'] = business_form.business_account
                data['business_amount'] = business_form.business_amount
                data['business_type'] = business_form.business_type
                data['business_type_str'] = business_form.get_business_type_display()
        except:
            pass
        return data

    def get_level(self, obj):
        data = {}
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            level = obj.level
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_customercser_mobile(self, obj):
        try:
            if obj.user:
                mobile = obj.user.mobile
                return mobile
            else:
                mobile = obj.customeruservice.customeruser.mobile
                return mobile
        except:
            return ''

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.win_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = obj.alidiscountcouponinfo_id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['amount'] = alidiscountcoupon.amount
            elif prize_type == 5:
                data['id'] = ''
                data['activity_name'] = f'{obj.point} 积分'
                data['activity_id'] = ''
                data['rule'] = f'{obj.point} 积分'
                data['amount'] = f''
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = obj.cashactivitydata_id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['amount'] = obj.cashactivitydata.amount
        except:
            pass
        return data


class BindCardOrderListModelSerializer(serializers.ModelSerializer):

    order_status_str = serializers.CharField(source='get_order_status_display', read_only=True)
    prize_status_str = serializers.CharField(source='get_prize_status_display', read_only=True)
    bank_type_sign_str = serializers.CharField(source='get_bank_type_sign_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customizeactivityflipcards = serializers.SerializerMethodField(read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    bank_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = BindCardOrder
        fields = ['id', 'order_status', 'order_status_str', 'prize_status', 'prize_status_str', 'create_time', 'user_received_account',
                  'customizeactivityflipcards', 'customeruservice', 'bank_type', 'bank_type_sign', 'bank_type_sign_str']

    def get_customeruservice(self, obj):
        data = {}
        data['mobile'] = ''
        data['unionid'] = ''
        try:
            customeruservice = obj.customeruservice
            data['mobile'] = customeruservice.mobile
            data['unionid'] = customeruservice.unionid
        except:
            pass
        return data

    def get_customizeactivityflipcards(self, obj):
        data = {}
        data['received_time'] = ''
        data['activity_name'] = ''
        try:
            customizeactivityflipcards = obj.customizeactivityflipcards
            if customizeactivityflipcards:
                data['received_time'] = customizeactivityflipcards.received_time.strftime("%Y-%m-%d %H:%M:%S")
                if customizeactivityflipcards.win_type in [1, 2]:
                    data['activity_name'] = customizeactivityflipcards.alidiscountcoupon.activity_name
                elif customizeactivityflipcards.win_type in [3]:
                    data['activity_name'] = customizeactivityflipcards.cashactivity.name
        except:
            pass
        return data

    def get_bank_type(self, obj):
        try:
            bank_type = obj.bank_type
            bank = BankType.objects.filter(bank_code=bank_type).first()
            if bank:
                return bank.bank_name
            else:
                return ''
        except:
            return ''


class BindCardOrderRetrieveModelSerializer(serializers.ModelSerializer):

    order_status_str = serializers.CharField(source='get_order_status_display', read_only=True)
    prize_status_str = serializers.CharField(source='get_order_status_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    success_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    bank_type = serializers.SerializerMethodField(read_only=True)
    customizeactivityflipcards = CustomizeActivityFlipCARDSListModelSerializer()
    bank_type_sign_str = serializers.CharField(source='get_bank_type_sign_display', read_only=True)

    class Meta:
        model = BindCardOrder
        fields = ['id', 'amount', 'order_status', 'order_status_str', 'prize_status', 'prize_status_str', 'create_time', 'user_received_account',
                  'out_trade_no', 'refund_id', 'transaction_id', 'message', 'bank_type', 'success_time', 'refund_time', 'customizeactivityflipcards',
                  'bank_type_sign', 'bank_type_sign_str']

    def get_bank_type(self, obj):
        try:
            bank_type = obj.bank_type
            bank = BankType.objects.filter(bank_code=bank_type).first()
            if bank:
                return bank.bank_name
            else:
                return ''
        except:
            return ''


class JoinCustomizeActivityListModelSerializer(serializers.ModelSerializer):

    is_join_str = serializers.CharField(source='get_is_join_display', read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    join_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = JoinCustomizeActivity
        fields = ['id', 'is_join', 'is_join_str', 'customeruservice', 'count', 'join_time']

    def get_customeruservice(self, obj):
        data = {}
        data['mobile'] = ''
        data['unionid'] = ''
        try:
            customeruservice = obj.customeruservice
            data['mobile'] = customeruservice.mobile
            data['unionid'] = customeruservice.unionid
        except:
            pass
        return data


class JoinCustomizeActivityRetrieveModelSerializer(serializers.ModelSerializer):

    is_join_str = serializers.CharField(source='get_is_join_display', read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    join_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # order_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = JoinCustomizeActivity
        fields = ['id', 'is_join', 'is_join_str', 'customeruservice', 'count', 'join_time']

    def get_customeruservice(self, obj):
        data = {}
        data['mobile'] = ''
        data['unionid'] = ''
        data['id'] = ''
        try:
            customeruservice = obj.customeruservice
            data['mobile'] = customeruservice.mobile
            data['unionid'] = customeruservice.unionid
            data['id'] = customeruservice.id
        except:
            pass
        return data

    def get_order_info(self, obj):
        if obj.is_join == 0:
            return []
        customizeactivity = obj.customizeactivity
        customizeactivitypayrules = customizeactivity.customizeactivitypayrules
        join_time = obj.join_time
        available_end_time = customizeactivity.available_end_time
        total_count = customizeactivitypayrules.total_count
        amount = customizeactivitypayrules.amount
        draw_counts = customizeactivitypayrules.draw_counts.split(',')
        limit_merchant_count_by_day = customizeactivitypayrules.limit_merchant_count_by_day
        if customizeactivitypayrules.is_limit_merchant == 0:
            queryset = get_point_record_db_model(obj.customeruservice_id).objects.filter(
                pay_time__gte=join_time,
                pay_time__lte=available_end_time,
                amount__gte=amount,
                customeruservice_id=obj.customeruservice_id,
                level__prov_id=7330
            ).values('shop_id').annotate(order_id=Min('id'))[0:total_count]
            if obj.is_join == 1:
                if len(queryset) >= total_count:
                    obj.is_join = 2
                obj.count = len(queryset)
                obj.save()
            order_id_list = []
            for order in queryset:
                order_id_list.append(order['order_id'])
        else:
            merchant_id_list = CustomizeActivityPayRulesLimitMerchant.objects.filter(customizeactivity_id=customizeactivity.id).values_list('merchant_id', flat=True)
            queryset = get_point_record_db_model(obj.customeruservice_id).objects.filter(
                pay_time__gte=join_time,
                pay_time__lte=available_end_time,
                amount__gte=amount,
                customeruservice_id=obj.customeruservice_id,
                merchant_id__in=merchant_id_list
            )
            order_id_list = []
            check_date_order = {}
            for order in queryset:
                if len(order_id_list) >= total_count:
                    break
                pay_time = f'{order.pay_time.strftime("%Y%m%d")}{order.merchant_id}'
                if pay_time not in check_date_order:
                    check_date_order[pay_time] = 0
                if check_date_order[pay_time] >= limit_merchant_count_by_day:
                    continue
                order_id_list.append(order.id)
                check_date_order[pay_time] = check_date_order[pay_time] + 1
            if obj.is_join == 1:
                if len(order_id_list) == total_count:
                    obj.is_join = 2
                obj.count = len(order_id_list)
                obj.save()
        queryset = get_point_record_db_model(obj.customeruservice_id).objects.filter(id__in=order_id_list)
        schedule_list = []
        for i in range(total_count):
            try:
                query = queryset[i]
                order_data = {}
                order_data['pay_time'] = query.pay_time.strftime("%Y-%m-%d %H:%M:%S")
                order_data['amount'] = query.amount
                order_data['count'] = f'第{i+1}笔'
                if query.bank_type == 'PSBC_DEBIT':
                    order_data['bank_type_sign_str'] = '邮储借记卡'
                    order_data['bank_type_sign'] = 1
                elif query.bank_type == 'PSBC_CREDIT':
                    order_data['bank_type_sign_str'] = '邮储信用卡'
                    order_data['bank_type_sign'] = 2
                else:
                    order_data['bank_type_sign_str'] = '其他'
                    order_data['bank_type_sign'] = 3
                merchant = query.merchant
                if merchant:
                    order_data['merchant_name'] = merchant.name
                    order_data['merchant_id'] = merchant.id
                else:
                    order_data['merchant_name'] = ''
                    order_data['merchant_id'] = ''
                if str(i + 1) in draw_counts:
                    if not query.customizeactivityflipcards:
                        customizeactivityrules = CustomizeActivityRules.objects.get(customizeactivity_id=customizeactivity.id, index=i + 1)
                        identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % obj.customeruservice_id}'
                        instance_data = dict()
                        instance_data['identify'] = identify
                        instance_data['customeruservice_id'] = obj.customeruservice_id
                        instance_data['mobile'] = obj.customeruservice.mobile
                        instance_data['gears'] = 1
                        instance_data['customizeactivity_id'] = customizeactivity.id
                        if customizeactivityrules.prize_type in [1, 2]:
                            instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                            instance_data['win_type'] = customizeactivityrules.prize_type
                        elif customizeactivityrules.prize_type in [3, 6]:
                            instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                            instance_data['win_type'] = customizeactivityrules.prize_type
                        instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                        if instance.win_type in [1, 2]:
                            instance.open_status = 2
                            instance.open_time = datetime.datetime.now()
                            instance.save()
                            alidiscountcoupon = instance.alidiscountcoupon
                            if alidiscountcoupon.remain_number <= 0:
                                x = list(customizeactivity.customizeactivityrules_set.filter(alidiscountcoupon__remain_number__gt=0).values_list('alidiscountcoupon_id', flat=True))
                                if x:
                                    shuffle(x)
                                    alidiscountcoupon = AliDiscountCoupon.objects.get(id=x[0])
                                    instance.alidiscountcoupon_id = alidiscountcoupon.id
                                    instance.save()
                                else:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                            activity_id = alidiscountcoupon.id
                            while True:
                                alidiscountcoupon = AliDiscountCoupon.objects.get(id=activity_id)
                                activity_origin_send_count = alidiscountcoupon.send_count
                                activity_origin_remain_number = alidiscountcoupon.remain_number
                                activity_new_send_count = activity_origin_send_count + 1
                                activity_new_remain_number = activity_origin_remain_number - 1
                                if activity_new_remain_number < 0:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                                result = AliDiscountCoupon.objects.filter(id=activity_id,send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                                if result == 0:
                                    continue
                                break
                            alidiscountcouponinfo_data = {}
                            alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                            alidiscountcouponinfo_data['level_id'] = instance.level_id
                            alidiscountcouponinfo_data['status'] = 0
                            alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                            out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % obj.customeruservice_id}'
                            alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                            alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                            alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                            instance.alidiscountcouponinfo_id = alidiscountcouponinfo.id
                            instance.save()
                        else:
                            instance.open_status = 2
                            instance.open_time = datetime.datetime.now()
                            instance.save()
                            cashactivity = instance.cashactivity
                            cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
                            if cashactivityrule.amount > cashactivity.remain_amount:
                                instance.open_status = 3
                                instance.win_type = 4
                                instance.open_time = datetime.datetime.now()
                                instance.save()
                            amount = cashactivityrule.amount
                            activity_id = cashactivity.id
                            while True:
                                activity = CashActivity.objects.get(id=activity_id)
                                activity_origin_take_amount = activity.take_amount
                                activity_origin_remain_amount = activity.remain_amount
                                if activity_origin_remain_amount < amount:
                                    instance.open_status = 3
                                    instance.win_type = 4
                                    instance.open_time = datetime.datetime.now()
                                    instance.save()
                                activity_new_take_amount = activity_origin_take_amount + amount
                                activity_new_remain_amount = activity_origin_remain_amount - amount
                                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                                if result == 0:
                                    continue
                                break
                            date_now = datetime.datetime.now()
                            activity_data = {}
                            activity_data['amount'] = amount
                            activity_data['create_time'] = date_now
                            activity_data['cash_activity_id'] = activity.id
                            activity_data['level_id'] = instance.level_id
                            activity_data['state'] = 1
                            identify = random_str()
                            nonce_str = random_str()
                            activity_data['identify'] = identify
                            activity_data['nonce_str'] = nonce_str
                            activity_data['desc'] = activity.name
                            activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%07d" % obj.customeruservice_id}'
                            activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                            activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                            instance.cashactivitydata_id = activity_dat.id
                            instance.amount = amount
                            instance.save()
                        query.customizeactivityflipcards_id = instance.id
                        query.save()
                    else:
                        instance = query.customizeactivityflipcards
                    order_data['open_status'] = instance.open_status
                    order_data['open_status_str'] = instance.get_open_status_display()
                    order_data['activity_name'] = instance.alidiscountcoupon.activity_name
                else:
                    order_data['open_status'] = ''
                    order_data['open_status_str'] = ''
                    order_data['activity_name'] = ''
                schedule_list.insert(0, order_data)
            except:
                pass
        return schedule_list


# class PointRecordOrderInfoSerializer(serializers.Serializer):
#
#     activity_name = serializers.SerializerMethodField(read_only=True)
#
#
#
#     def get_activity_name(self, obj):
#         try:
#             order_id_dict = self.context.get('order_id_dict', None)
#             if obj.


class CustomerUserViceListModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUserVice
        fields = ['id', 'unionid', 'is_subscribe', 'is_wyh_customer', 'mobile', 'level_name', 'obtain_point']

    def get_level_name(self, obj):
        try:
            return obj.level.city_name
        except:
            return ''


class CustomerUserViceRetrieveModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    action_area = serializers.SerializerMethodField(read_only=True)
    action_time = serializers.SerializerMethodField(read_only=True)
    bank_type = serializers.SerializerMethodField(read_only=True)
    statistics = serializers.SerializerMethodField(read_only=True)
    location = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUserVice
        fields = ['id', 'unionid', 'is_subscribe', 'is_wyh_customer', 'mobile', 'level_name', 'obtain_point', 'username',
                  'operator', 'province', 'city', 'realname', 'idcode', 'action_area', 'action_time', 'bank_type', 'avatar',
                  'statistics', 'location']

    def get_location(self, obj):
        data = {}
        try:
            customeruservicearea = obj.customeruservicearea_set.all().first()
            if customeruservicearea:
                level = customeruservicearea.level
                if level.latitude:
                    data['latitude'] = level.latitude
                    data['longitude'] = level.longitude
                else:
                    data['latitude'] = '23.141173'
                    data['longitude'] = '113.345357'
            else:
                data['latitude'] = '23.141173'
                data['longitude'] = '113.345357'
        except:
            data['latitude'] = '23.141173'
            data['longitude'] = '113.345357'
        return data

    def get_action_area(self, obj):
        data = []
        try:
            customeruservicearea_set = obj.customeruservicearea_set.all()
            for customeruservicearea in customeruservicearea_set:
                data.append(customeruservicearea.level.name)
        except:
            pass
        return data

    def get_action_time(self, obj):
        data = []
        try:
            customeruservicetime_set = obj.customeruservicetime_set.all().exclude(action_time=7)
            for customeruservicetime in customeruservicetime_set:
                data.append(customeruservicetime.get_action_time_display())
        except:
            pass
        return data

    def get_bank_type(self, obj):
        data = []
        try:
            customeruservicebanktype_set = obj.customeruservicebanktype_set.all()
            for customeruservicebanktype in customeruservicebanktype_set:
                bank_type = BankType.objects.filter(bank_code=customeruservicebanktype.bank_code).first()
                if bank_type:
                    data.append(bank_type.bank_name)
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:

            return obj.level.city_name
        except:
            return ''

    def get_statistics(self, obj):
        data = {}
        data['count'] = 0
        data['amount'] = 0
        try:
            conn = pymysql.connect(host=settings.DATABASES['business_custmoer_order_data']['HOST'],
                                   port=settings.DATABASES['business_custmoer_order_data']['PORT'],
                                   database=settings.DATABASES['business_custmoer_order_data']['NAME'],
                                   user=settings.DATABASES['business_custmoer_order_data']['USER'],
                                   password=settings.DATABASES['business_custmoer_order_data']['PASSWORD'])
            cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
            sql = f'''
            SELECT COUNT(id) AS count,SUM(money) AS amount FROM tb_o_point_order_info_{obj.id % 900} WHERE customeruservice_id={obj.id};
            '''
            cursor.execute(sql)
            row = cursor.fetchone()
            cursor.close()
            conn.close()
            if row:
                data['count'] = row['count']
                data['amount'] = row['amount']
        except:
            pass
        return data


class MerchantEightEightDrawListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightDraw
        fields = ['id', 'create_time', 'amount', 'received_time', 'state', 'state_str', 'business_no', 'level_name', 'mobile',
                  'merchant', 'index']

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            data['merchant_id'] = merchant.id
            data['merchant_short_name'] = merchant.short_name
        except:
            pass
        return data

    def get_amount(self, obj):
        try:
            prize = MerchantEightEightActivityPrize.objects.get(id=obj.win_type)
            if prize.prize_type == 1:
                return f'¥{obj.amount}'
            else:
                return prize.prize_name
            # if obj.win_type == 6:
            #     return '谢谢参与'
            # else:
            #     return f'¥{obj.amount}'
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''


class MerchantEightEightDrawRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    alidiscountcouponinfo_list = serializers.SerializerMethodField(read_only=True)
    channel = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightDraw
        fields = ['id', 'create_time', 'amount', 'received_time', 'state', 'state_str', 'business_no', 'level',
                  'login_id', 'realname', 'mobile', 'payment_no', 'mobile', 'merchant', 'return_msg', 'activity_name',
                  'alidiscountcouponinfo_list', 'channel']

    def get_channel(self, obj):
        try:
            return f'{obj.channel.name}({obj.channel.mchid})'
        except:
            return ''

    def get_alidiscountcouponinfo_list(self, obj):
        try:
            alidiscountcouponinfo_list = obj.alidiscountcouponinfo_list
            if alidiscountcouponinfo_list:
                queryset = AliDiscountCouponInfo.objects.filter(id__in=json.loads(alidiscountcouponinfo_list))
                return AliDiscountCouponInfoListModelSerializer(queryset, many=True).data
            return []
        except:
            return []

    def get_activity_name(self, obj):
        return '深圳达标商户有礼'

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            data['merchant_id'] = merchant.id
            data['merchant_short_name'] = merchant.short_name
        except:
            pass
        return data

    def get_amount(self, obj):
        try:
            prize = MerchantEightEightActivityPrize.objects.get(id=obj.win_type)
            if prize.prize_type == 1:
                return f'¥{obj.amount}'
            else:
                return prize.prize_name
            # if obj.win_type == 6:
            #     return '谢谢参与'
            # else:
            #     return f'¥{obj.amount}'
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data

    def get_mobile(self, obj):
        try:
            return obj.merchantuser.mobile
        except:
            return ''


class MerchantBusinessQRCodeListModelSerializer(serializers.ModelSerializer):

    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)
    is_c_bind_str = serializers.CharField(source='get_is_c_bind_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    c_bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'is_bind', 'is_bind_str', 'bind_time', 'merchant', 'inviter_count', 'inviter_total_count',
                  'is_c_bind', 'is_c_bind_str', 'c_bind_time']

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['city_name'] = level.city_name
                data['district_name'] = level.district_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data


class MerchantBusinessQRCodeRetrieveModelSerializer(serializers.ModelSerializer):

    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)
    is_c_bind_str = serializers.CharField(source='get_is_c_bind_display', read_only=True)
    is_achieve_str = serializers.CharField(source='get_is_achieve_display', read_only=True)
    award_status_str = serializers.CharField(source='get_award_status_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    award_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    c_bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)
    manager = serializers.SerializerMethodField(read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    cashactivitydata = serializers.SerializerMethodField(read_only=True)
    sn_qrcode = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'is_bind', 'is_bind_str', 'bind_time', 'merchant', 'manager', 'is_c_bind', 'is_c_bind_str', 'c_bind_time', 'customeruservice',
                  'award_status', 'award_status_str', 'is_achieve', 'is_achieve_str', 'award_time', 'cashactivitydata', 'sn_qrcode']

    def get_sn_qrcode(self, obj):
        try:
            if not obj.sn_qrcode:
                sn_url = f'https://qrcode.sutpay.com/business/business_district/?shop_id={obj.sn}'
                # sn_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                sn_qrcode = make_qrcode4(obj.sn, sn_url, None)
                obj.sn_url = sn_url
                obj.sn_qrcode = sn_qrcode
                obj.save()
                return f'https://circle.sutpay.cn/{sn_qrcode}'
            else:
                return obj.sn_qrcode.url
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['city_name'] = level.city_name
                data['district_name'] = level.district_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_manager(self, obj):
        try:
            user = obj.user
            if user:
                return f'{user.nickname}({user.mobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''

    def get_customeruservice(self, obj):
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                return f'{customeruservice.realname}({customeruservice.mobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''

    def get_cashactivitydata(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['received_time'] = ''
        data['amount'] = ''
        try:
            cashactivitydata = obj.cashactivitydata
            if cashactivitydata:
                cash_activity = cashactivitydata.cash_activity
                data['id'] = cashactivitydata.id
                data['activity_name'] = cash_activity.name
                data['amount'] =  cashactivitydata.amount
                data['state'] = cashactivitydata.state
                data['received_time'] = cashactivitydata.received_time.strftime("%Y-%m-%d %H:%M:%S")
            else:
                if obj.is_bind == 1:
                    companyuser = obj.user
                    companyuser_id = companyuser.id
                    date_now = datetime.datetime.now()
                    nonce_str = random_str()
                    cash_activity_id = 355
                    amount = Decimal('5')
                    cash_activity = CashActivity.objects.get(id=cash_activity_id)
                    cashactivitydata_data = {}
                    cashactivitydata_data['companyuser_id'] = companyuser_id
                    cashactivitydata_data['cash_activity_id'] = cash_activity.id
                    cashactivitydata_data['amount'] = amount
                    cashactivitydata_data['create_time'] = date_now
                    cashactivitydata_data['nonce_str'] = nonce_str
                    cashactivitydata_data['desc'] = cash_activity.name
                    cashactivitydata_data['mobile'] = companyuser.mobile
                    cashactivitydata_data['openid'] = companyuser.openid
                    cashactivitydata_data['appid'] = 'wxb67b94c00d7cd83f'
                    cashactivitydata_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % companyuser_id}'
                    cashactivitydata = CashActivityData.objects.create(**cashactivitydata_data)
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        activity_origin_take_amount = activity.take_amount
                        activity_origin_remain_amount = activity.remain_amount
                        activity_new_take_amount = activity_origin_take_amount + amount
                        activity_new_remain_amount = activity_origin_remain_amount - amount
                        result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                             remain_amount=activity_origin_remain_amount,
                                                             id=cash_activity_id).update(
                            take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                        if result == 0:
                            continue
                        break
                    obj.cashactivitydata_id = cashactivitydata.id
                    # obj.is_achieve = 1
                    # obj.award_time = CustomerUserViceInviterRecord.objects.filter(qrcode_id=obj.id, is_inviter=1)[1].inviter_time
                    obj.save()
                    data['id'] = cashactivitydata.id
                    data['activity_name'] = cash_activity.name
                    data['amount'] = cashactivitydata.amount
                    data['state'] = cashactivitydata.state
                    data['received_time'] = cashactivitydata.received_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        return data


class MerchantBusinessQRCodeVisitListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customeruservice = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCodeVisit
        fields = ['id', 'create_time', 'customeruservice']

    def get_customeruservice(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        data['openid'] = ''
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                data['realname'] = customeruservice.username
                data['mobile'] = customeruservice.mobile
                data['openid'] = customeruservice.wyh_openid
        except:
            pass
        return data


class CustomerUserViceInviterRecordListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    inviter_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    inviter = serializers.SerializerMethodField(read_only=True)
    is_inviter_str = serializers.CharField(source='get_is_inviter_display', read_only=True)

    class Meta:
        model = CustomerUserViceInviterRecord
        fields = ['id', 'create_time', 'customeruservice', 'is_inviter', 'is_inviter_str', 'inviter_time', 'inviter_time', 'inviter']

    def get_customeruservice(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        data['openid'] = ''
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                data['realname'] = customeruservice.username
                data['mobile'] = customeruservice.mobile
                data['openid'] = customeruservice.wyh_openid
        except:
            pass
        return data

    def get_inviter(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        try:
            customeruservice = obj.inviter
            if customeruservice:
                data['realname'] = customeruservice.username
                data['mobile'] = customeruservice.mobile
        except:
            pass
        return data


class AliDiscountCouponDistributionPlatformModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = AliDiscountCouponDistributionPlatform
        fields = ['id', 'platform_name']


class AliDiscountCouponSyncWYHRecordModelSerializer(serializers.ModelSerializer):

    alidiscountcoupon = serializers.SerializerMethodField(read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    finish_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sync_status_str = serializers.CharField(source='get_sync_status_display', read_only=True)

    class Meta:
        model = AliDiscountCouponSyncWYHRecord
        fields = ['id', 'alidiscountcoupon', 'create_user', 'create_time', 'finish_time', 'sync_status', 'sync_status_str', 'remark']

    def get_alidiscountcoupon(self, obj):
        data = {}
        data['activity_name'] = ''
        data['activity_id'] = ''
        try:
            alidiscountcoupon = obj.alidiscountcoupon
            data['activity_name'] = alidiscountcoupon.activity_name
            data['activity_id'] = alidiscountcoupon.id
        except:
            pass
        return data

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class MerchantEightEightActivityModelSerializer(serializers.ModelSerializer):

    activity_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    level_name = serializers.SerializerMethodField(read_only=True)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_status = serializers.SerializerMethodField(read_only=True)
    activity_type = serializers.SerializerMethodField(read_only=True)
    new_prize = serializers.SerializerMethodField(read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)

    class Meta:
        model = MerchantEightEightActivity
        fields = ['id', 'activity_id', 'activity_name', 'activity_start_time', 'activity_end_time', 'activity_description', 'level_name',
                  'activity_status', 'activity_status_str', 'total_amount', 'total_count', 'activity_type', 'activity_type_str',
                  'new_prize']

    def get_new_prize(self, obj):
        return 0

    def get_activity_type(self, obj):
        if obj.id == 47:
            return 1
        elif obj.id == 50:
            return 4
        else:
            return obj.activity_type

    def get_activity_status(self, obj):
        if obj.activity_status == 1:
            if obj.activity_start_time < datetime.datetime.now():
                obj.activity_status = 2
                obj.save()
        elif obj.activity_status == 2:
            if obj.activity_end_time < datetime.datetime.now():
                obj.activity_status = 3
                obj.save()
        return obj.activity_status

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class MerchantEightEightWhiteTableModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantEightEightWhiteTable
        fields = ['id', 'merchant', 'business_no']

    def get_merchant(self, obj):
        data = {}
        data['subject_type_str'] = ''
        data['subject_type'] = ''
        data['merchant_id'] = ''
        data['name'] = ''
        data['level_name'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['subject_type_str'] = merchant.get_subject_type_display()
                data['subject_type'] = merchant.subject_type
                data['merchant_id'] = merchant.id
                data['name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data


class MerchantEightEightActivityOrderModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    is_standard = serializers.SerializerMethodField(read_only=True)
    trade_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)

    class Meta:
        model = MerchantEightEightActivityOrder
        fields = ['id', 'merchant', 'business_no', 'is_standard', 'trade_amount', 'trade_time']

    def get_merchant(self, obj):
        data = {}
        data['subject_type_str'] = ''
        data['subject_type'] = ''
        data['merchant_id'] = ''
        data['name'] = ''
        data['level_name'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['subject_type_str'] = merchant.get_subject_type_display()
                data['subject_type'] = merchant.subject_type
                data['merchant_id'] = merchant.id
                data['name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data

    def get_is_standard(self, obj):
        if obj.is_standard == 2:
            return 1
        return obj.is_standard


class MerchantEightEightActivityPrizeModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)

    class Meta:
        model = MerchantEightEightActivityPrize
        fields = ['id', 'prize_type', 'amount', 'prize_name', 'count', 'prize_type_str', 'second_count']


class ExpressTypeModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExpressType
        fields = ('id', 'express_type_name', 'logo')


class OrderAdvanceModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderAdvance
        fields = ('id', 'create_time', 'remark', 'status', 'status_str', 'user')

    def get_user(self, obj):
        data = {}
        data['user_role'] = ''
        data['user_name'] = ''
        try:
            if obj.user:
                data['user_role'] = obj.user.role.name
                data['user_name'] = obj.user.nickname
            elif obj.merchantuser:
                data['user_role'] = '商家'
                data['user_name'] = obj.merchantuser.mobile
            else:
                data['user_role'] = '消费者'
                if obj.customeruser:
                    data['user_name'] = obj.customeruser.username
                else:
                    data['user_name'] = obj.customeruservice.username
        except:
            pass
        return data


class ExpressQuestListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_enter_str = serializers.CharField(source='get_is_enter_display', read_only=True)
    user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ExpressQuest
        fields = ('id', 'create_time', 'file', 'logs_file', 'is_enter_str', 'is_enter', 'line_number', 'success_number', 'error_number', 'user')

    def get_user(self, obj):
        try:
            if obj.user:
                return obj.user.nickname
            else:
                return f'商户({obj.merchantuser.mobile})'
        except:
            return ''


class AliDiscountCouponGoodsAvailableListModelSerializer(serializers.ModelSerializer):

    goods = GoodsListModelSerializer()

    class Meta:
        model = AliDiscountCouponGoodsAvailable
        fields = ('id', 'goods')


class MerchantMonthlyBillListModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model =  MerchantMonthlyBill
        fields = ('id', 'bill_name', 'bill_time', 'order_amount', 'order_count', 'separate_amount', 'restitution_amount', 'merchant', 'settlement_amount',
                  'merchant_id', 'merchant_name', 'level_name')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class MerchantMonthlyBillRetrieveModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model =  MerchantMonthlyBill
        fields = ('id', 'bill_name', 'bill_time', 'order_amount', 'order_count', 'separate_amount', 'restitution_amount',
                  'settlement_amount', 'bill_file', 'merchant_id', 'merchant_name', 'level')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class ExpressListModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str')

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class ExpressRetrieveModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    expressplan_set = serializers.SerializerMethodField(read_only=True)
    order_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str', 'expressplan_set', 'order_set')

    def get_order_set(self, obj):
        try:
            order_id_list = obj.expressorderrelevance_set.all().values_list('order_id', flat=True)
            order_set = OrderInfo.objects.filter(id__in=list(order_id_list))
            return OrderInfoListModelSerializer(order_set, many=True).data
        except:
            return []

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class YSHAreaCodeModelSerializer(serializers.ModelSerializer):

    level_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = YSHAreaCode
        fields = ('id', 'code', 'prov_name', 'city_name', 'district_name', 'level', 'level_str', 'name')

    def get_level_str(self, obj):
        try:
            if obj.level == 1:
                return '省'
            elif obj.level == 2:
                return '市'
            elif obj.level == 3:
                return '区'
            else:
                return ''
        except:
            return ''


class YSHContractModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = YSHContract
        fields = ('id', 'supplierCode', 'supplierName', 'contractCode', 'contractName', 'taxRate')


class OrderInfoGROUPListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    group_status_str = serializers.CharField(source='get_group_status_display', read_only=True)
    order_num = serializers.SerializerMethodField(read_only=True)
    order = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfoGROUP
        fields = ['id', 'create_time', 'group_status', 'group_status_str', 'expired_time', 'group_order_num', 'order', 'order_num']

    def get_order(self, obj):
        data = {}
        data['goods_id'] = ''
        data['goods_name'] = ''
        data['merchant_name'] = ''
        data['merchant_id'] = ''
        data['level_name'] = ''
        data['order_id'] = ''
        data['id'] = ''
        data['default_image'] = ''
        data['price'] = ''
        data['group_price'] = ''
        try:
            order = OrderInfo.objects.get(id=obj.order_id)
            goods = obj.goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['merchant_name'] = goods.merchant.name
            data['merchant_id'] = goods.merchant_id
            if order.level:
                data['level_name'] = f'{order.level.name}(分店)'
            else:
                data['level_name'] = '总店'
            data['order_id'] = order.order_id
            data['id'] = order.id
            data['default_image'] = goods.default_image.url
            data['price'] = goods.price
            data['group_price'] = goods.group_price
        except:
            pass
        return data

    def get_order_num(self, obj):
        order_num =  OrderInfo.objects.filter(state__in=[2,3,15,8], group_id=obj.id).count()
        return order_num


class OrderInfoGROUPRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    group_status_str = serializers.CharField(source='get_group_status_display', read_only=True)
    order = serializers.SerializerMethodField(read_only=True)
    order_num = serializers.SerializerMethodField(read_only=True)
    order_lists = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfoGROUP
        fields = ['id', 'create_time', 'group_status', 'group_status_str', 'expired_time', 'group_order_num', 'order', 'order_lists',
                  'order_num']

    def get_order(self, obj):
        data = {}
        data['goods_id'] = ''
        data['goods_name'] = ''
        data['merchant_name'] = ''
        data['merchant_id'] = ''
        data['level_name'] = ''
        data['order_id'] = ''
        data['id'] = ''
        data['price'] = ''
        data['group_price'] = ''
        try:
            order = OrderInfo.objects.get(id=obj.order_id)
            goods = obj.goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['merchant_name'] = goods.merchant.name
            data['merchant_id'] = goods.merchant_id
            if order.level:
                data['level_name'] = f'{order.level.name}(分店)'
            else:
                data['level_name'] = '总店'
            data['order_id'] = order.order_id
            data['id'] = order.id
            data['price'] = goods.price
            data['group_price'] = goods.group_price
        except:
            pass
        return data

    def get_order_lists(self, obj):
        data = []
        try:
            order_set = OrderInfo.objects.filter(group_id=obj.id)
            serializer_data = OrderInfoListModelSerializer(order_set, many=True).data
            for i in serializer_data:
                if str(i['id']) == obj.order_id:
                    i['group'] = '主'
                else:
                    i['group'] = '从'
                data.append(i)
        except:
            pass
        return data

    def get_order_num(self, obj):
        order_num =  OrderInfo.objects.filter(state__in=[2,3,15,8], group_id=obj.id).count()
        return order_num


class OrderSchengleListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    order_state_str = serializers.CharField(source='get_order_state_display', read_only=True)
    orderinfo = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderSchengle
        fields = ['id', 'orderinfo', 'orderId', 'formCode', 'create_time', 'order_state', 'order_state_str', 'resultDesc']

    def get_orderinfo(self, obj):
        data = {}
        try:
            order = obj.order
            data['id'] = order.id
            data['order_id'] = order.order_id
            data['state'] = order.state
            data['state_str'] = order.get_state_display()
            goods = OrderGoods.objects.filter(order_id=order.id).first().goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['default_image'] = goods.default_image.url
            merchant = order.merchant
            data['merchant_id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['reserved_mobile'] = order.reserved_mobile
        except:
            pass
        return data


class OrderSchengleRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    coupons = serializers.SerializerMethodField(read_only=True)
    orderinfo = serializers.SerializerMethodField(read_only=True)
    order_state_str = serializers.CharField(source='get_order_state_display', read_only=True)

    class Meta:
        model = OrderSchengle
        fields = ['id', 'orderId', 'formCode', 'create_time', 'order_state', 'order_state_str', 'resultDesc',
                  'end_time', 'start_time', 'coupons', 'orderinfo']

    def get_coupons(self, obj):
        try:
            order = obj.order
            if order.order_type == 3:
                sd_order = obj
                if sd_order.order_state in [4, 2] and sd_order.end_time >= datetime.datetime.now():
                    result = schengle.query_order({"outTradeNo": sd_order.outTradeNo})
                    if result['resultCode'] == 'success':
                        couponInfoList = result['data']['couponDetailList']
                        use_time = None
                        for couponInfo in couponInfoList:
                            couponId = couponInfo['couponId']
                            if couponInfo['status'] == 5:
                                use_time = couponInfo['useTime']
                                OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=5,
                                                                                              useTime=couponInfo['useTime'],
                                                                                              useShopCode=couponInfo['useShopCode'],
                                                                                              useShopName=couponInfo['useShopName'],
                                                                                              useCityCode=couponInfo['useCityCode'],
                                                                                              useCityName=couponInfo['useCityName'],
                                                                                              )
                                GoodsCoupons.objects.filter(coupons_id=couponId).update(use_time=couponInfo['useTime'], status=2)
                                sd_order.order_state = 4
                                sd_order.save()
                            elif couponInfo['status'] == 6:
                                use_time = couponInfo['useTime']
                                OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=6)
                                GoodsCoupons.objects.filter(coupons_id=couponId).update(status=3)
                        check_coupons = OrderSchengleCoupons.objects.filter(order_id=order.id, coupon_state=1)
                        if not check_coupons:
                            sd_order.order_state = 5
                            sd_order.save()
                            order.state = 3
                            order.use_time = use_time
                            order.save()
        except:
            pass
        couponset = OrderSchengleCoupons.objects.filter(order_id=obj.order_id)
        return OrderSchengleCouponsModelSerializer(couponset, many=True).data

    def get_orderinfo(self, obj):
        data = {}
        try:
            order = obj.order
            data['id'] = order.id
            data['order_id'] = order.order_id
            data['state'] = order.state
            data['state_str'] = order.get_state_display()
            goods = OrderGoods.objects.filter(order_id=order.id).first().goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['default_image'] = goods.default_image.url
            merchant = order.merchant
            data['merchant_id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['reserved_mobile'] = order.reserved_mobile
        except:
            pass
        return data


class OrderSchengleCouponsModelSerializer(serializers.ModelSerializer):

    createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    startTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    endTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    useTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    service_name = serializers.SerializerMethodField(read_only=True)
    coupon_state_str = serializers.CharField(source='get_coupon_state_display', read_only=True)

    class Meta:
        model = OrderSchengleCoupons
        fields = ['id', 'couponId', 'useTime', 'createTime', 'startTime', 'endTime', 'coupon_state', 'coupon_state_str',
                  'useShopCode', 'useShopName', 'useCityCode', 'useCityName', 'service_name']

    def get_service_name(self, obj):
        try:
            dict1 = {
                "5264": "全套精洗（全车型）",
                "5221": "臭氧杀菌（不含洗车）",
                "4080": "汽车桑拿-空调清洗",
                "5058": "抛光打蜡（全车型）",
                "5261": "内饰清洗（全车型）",
            }
            return dict1[obj.serviceId]
        except:
            return ''


class CashActivityDataKeguanListModelSerializer(serializers.ModelSerializer):

    push_status_str = serializers.CharField(source='get_push_status_display', read_only=True)
    push_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_no = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityDataKeguan
        fields = ['id', 'push_status_str', 'push_status', 'push_time', 'return_msg', 'cashactivitydata_id', 'payment_no']

    def get_payment_no(self, obj):
        try:
            return obj.cashactivitydata.payment_no
        except:
            return ''